PHP - Mysqli::__construct
This line of PHP
mysqli::__construct($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname); returns Quote Fatal error: Non-static method mysqli::mysqli() cannot be called statically in Why does it do this? I want to use the OOP MySQLi methods in PHP and NO procedural PHP Similar TutorialsHi, I'm fairly new to OOP so please bare with me. I've been given to understand __construct is put forth in order to do that as soon as the object is created. Now I've created an object to control sessions. so here is my construct code includes a function within that object and session_start(). However, I get the error that the function within that object is non-existent but the function is right underneath the __construct function. should I put __construct last thing in my object? ANy help on this issue would be excellent! Thank you. I am trying to familiarize myself with using classes and I have a question regarding the use of __construct and __destruct. When using both, should the functions be public or private?
Hi! I'm new here private PDO $connection; function __construct(PDO $connection) { $this->connection = $connection; connect.php class dbh{ private $host = "localhost"; private $user = "root"; private $pwd = ""; private $dbname = "cms"; protected function connect() { $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname; $pdo = new PDO ($dsn, $this->user, $this->pwd); $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); return $pdo; } }
function.php // not a whole code class CategoriesData extends dbh{ public function getAllCategories() { $sql = "SELECT * FROM categories_tbl"; $stmt = $this->connect()->query($sql); while ($row = $stmt->fetch()){ echo $row['category_name'] . '<br>'; } } public function getCategoryName() { $sql = "SELECT category_name FROM categories_tbl"; $stmt = $this->connect()->prepare($sql); $stmt->execute(); $category = $stmt->fetch(PDO::FETCH_OBJ); if($category == null) { return null; }else { return $category->category_name; } } public function getCategoryDetials() { $sql = "SELECT * FROM categories_tbl"; $stmt = $this->connect()->prepare($sql); $stmt->execute(); $result = $stmt->fetchAll((PDO::FETCH_OBJ)); return $result; } public function addCategory ($filter_name, $filter_title, $filter_description, $filter_slug) { $sql = "INSERT INTO categories_tbl (category_name, category_title, category_description, category_slug) VALUES (?, ?, ?, ?)"; $stmt = $this->connect()->prepare($sql); $stmt->execute([$filter_name, $filter_title, $filter_description, $filter_slug]); } public function deleteCategory($delete_category_id) { $sql = "DELETE FROM categories_tbl WHERE category_id = ?"; $stmt = $this->connect()->prepare($sql); $stmt->execute([$delete_category_id]); } } }
Hello, I'm in need of help. Sometimes my PHP reads XML from a ssh and it tends to fail at times. Heres my complete error: Code: [Select] [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: Entity: line 3: parser error : Premature end of data in tag info line 2 in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Warning: SimpleXMLElement::__construct() [<a href='simplexmlelement.--construct'>simplexmlelement.--construct</a>]: ^ in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 [04-Aug-2010 18:03:16] PHP Fatal error: Uncaught exception 'Exception' with message 'String could not be parsed as XML' in /home/nmdgamin/public_html/private/includes/functions/revision.php:69 Stack trace: #0 /home/nmdgamin/public_html/private/includes/functions/revision.php(69): SimpleXMLElement->__construct('<?xml version="...') #1 /home/nmdgamin/public_html/private/includes/functions/update.php(16): CheckRemoteRevision('SpaceBuild') #2 /home/nmdgamin/public_html/prv_updater.php(13): Update() #3 {main} thrown in /home/nmdgamin/public_html/private/includes/functions/revision.php on line 69 Remote function: function CheckRemoteRevision($Name){ if($Name){ if($Query = MySQLQuery('SELECT name, url, sv_revision FROM data WHERE name=\''. $Name .'\';')){ if($XMLFile = shell_exec('svn info \''. $Query['url'] .'\' --username anonsvn --password anonsvn --xml')){ if($DCheck = explode(' ', $XMLFile)){ if($DCheck[0] == 'svn:'){ $Revision = '0'; $Result = MySQLQuery('UPDATE data SET sv_revision=\''. $Revision .'\' WHERE name=\''. $Query['name'] .'\';'); return False; } } $XML = new SimpleXMLElement($XMLFile); foreach($XML->entry as $Attribute){ $Revision = $Attribute['revision']; } if($Query['sv_revision'] < $Revision || $Query["sv_revision"] != $Revision){ $Result = MySQLQuery('UPDATE data SET sv_revision=\''. $Revision .'\' WHERE name=\''. $Query['name'] .'\';'); } return $Revision; }else{ return False; } }else{ return False; } }else{ return False; } } How would I full proof this from getting this error again, It seems to happen at completely random times. I'm not very good with XML in PHP Thanks! Hi all If there a better way of setting variables within classes than taking it through the __construct and setting via $this ?? e.g. class SectionsConnect { protected $var; public function __construct($var){ $this->var= $var; } } Can you not set the variable automatically as it comes in through the __construct? Thanks Magnetica Hey there, This has me stumped here. I'm supplying an array as a valid argument to the class like so: $mysql_configuration = array( 'MySQL_Host' => "localhost", 'MySQL_Username' => "fdsfdsfsdfsd", 'MySQL_Password' => "sdf-sdf543", 'MySQL_Database' => "sfsdfsdfsdf"); $radio_core = array('Main' => new Radio_Core($mysql_configuration), 'Requests' => new Radio_Requests, 'Accounts' => new Radio_Accounts, 'Content' => new Radio_Content); And here is my small class: class Radio_Core { public $mysql_handle; function __construct($mysql_array) { $this->mysql_handle = mysql_connect($mysql_array['MySQL_Host'], $mysql_array['MySQL_Username'], $mysql_array['MySQL_Password']); if(!$this->mysql_handle) { die("The station failed to connect to the MySQL database."); } else { mysql_select_db($mysql_array['MySQL_Database'], $this->mysql_handle); } return 1; } } And when it is called I am prompted with the error that the argument is missing for it? Quote Warning: Missing argument 1 for Radio_Co :__construct(), called in /home/atomnetw/public_html/Chris-Martino.com/projects/radio/index.php on line 10 and defined in /home/atomnetw/public_html/Chris-Martino.com/projects/radio/Core/radio.class.php on line 15 Warning: mysql_connect() [function.mysql-connect]: Access denied for user 'atomnetw'@'localhost' (using password: NO) in /home/atomnetw/public_html/Chris-Martino.com/projects/radio/Core/radio.class.php on line 17 Thanks for your time! Hi, I'm having a bit of a problem understanding why I'm not able to use the class I'm extending off of functions. I have a category class that extends off my core class, inside that category class, I'm able to use the core functions and variables inside all custom functions, but not the __construct function. So, to be clear, inside class class, I'm able to call $this->core->function() inside custom functions, such as function add_parent(), but not the __construct function. Why is this happening, what is the logic behind this? This is how I'm extending the class off of the core class: Code: [Select] <?php $core = new core; $parent = new parents; $parent->core =& $core; ?> With this, like I said, I'm able to use all of my core functions inside all other classes called this way, so inside all of the other classes I can do: Code: [Select] <?php $this->core->function(); ?>everywhere besides __construct(). Do I not have the class called properly? Do I need to pass my core class through differently? How can I fix this? Thanks. Can I not pass references into class properities from outside the object? class db_manipulation { private $connection = NULL; function __construct(&$database_connection) { $this->connection = $database_connection; if (!$this->connection) die('couldnt connection to database'); } function __destruct() { mysqli_close($this->connection); } } Results in: Warning: mysqli_close() [function.mysqli-close]: Couldn't fetch mysqli in When running the following code i get the error: Call to undefined method mysqli::errno() the code: $conn = new mysqli(HOST, USER, PASSWORD, DATABASE); if ($conn->errno() !== 0) { $msg = $conn->error(); throw new connErrorException($msg, 'Connect'); } I am fairly new to classes but as i understand it this should be correct. I am using mysql 5.1 so mysqli is on by default. I have even checked the php ini and everything looks fine there in respect to this. Any advice?
The below code produces a dropdown and when a selection is made and submitted produces --------------------------------------------------------------------------- <!DOCTYPE><html><head> <title>lookup menu</title> </head> <body><center><b> <form name="form" method="post" action=""> <?php // error_reporting(0); error_reporting(E_ALL ^ E_NOTICE); include 'homedb-connect.php'; //This creates the drop down box echo "<select name= 'target'>"; echo '<option value="">'.'--- Select account ---'.'</option>'; $query = mysqli_query($con,"SELECT target FROM lookuptbl"); $query_display = mysqli_query($con,"SELECT * FROM lookuptbl"); while($row=mysqli_fetch_array($query)) {echo "<option value='". $row['target']."'>".$row['target'] .'</option>';} echo '</select>'; ?> <input type="submit" name="submit" value="Submit"/> </form><center> <?php // error_reporting(0); error_reporting(E_ALL ^ E_NOTICE); include 'homedb-connect.php'; if(isset($_POST['target'])) { $name = $_POST['target']; $fetch="SELECT target, purpose, user, password, email, visits, date, saved FROM lookuptbl WHERE target = '".$name."'"; $result = mysqli_query($con,$fetch); if(!$result) {echo "Error:".(mysqli_error($con));} //display the table echo '<table border="1"><tr><td bgcolor="#ccffff" align="center">lookup menu</td></tr> <tr><td> <table border="1"> <tr> <td> Target </td> <td> Purpose </td> <td> User </td> <td> Password </td> <td> Email </td> <td> Visits </td> <td> Date </td> <td> Saved </td> </tr>'; while($data=mysqli_fetch_row($result)) { $url= "http://localhost/home/crud-link.php?target=". $data[0]; $link= '<a href="'.$url.'">'. $data[0]. '</a>'; echo ("<tr><td> $link </td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td> <td>$data[4]</td><td>$data[5]</td><td>$data[6]</td><td>$data[7]</td></tr>"); } echo '</table> </td></tr></table>'; } ?> </body></html>
I have just started using MySQLi and am clueless it is giving me the follow errors in which i do not understand
Warning: mysqli_select_db() expects exactly 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 23 Notice: Trying to get property of non-object in C:\xampp\htdocs\Login\connect.php on line 25 Notice: Use of undefined constant mysqli - assumed 'mysqli' in C:\xampp\htdocs\Login\connect.php on line 32 Warning: mysqli_query() expects parameter 1 to be mysqli, string given in C:\xampp\htdocs\Login\connect.php on line 32 Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in C:\xampp\htdocs\Login\connect.php on line 33 can someone please explain to me why i am getting these? and my code is $mysqli_db = mysqli_select_db("$db_name"); if($mysqli_db->connect_errno) { printf("Database not found: %s\n", $mysql->connect_error); exit(); } $sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $result = mysqli_query($sql); $row = mysqli_fetch_assoc($result);I just got rid off most the errors the only ones left are Warning: mysqli_query() expects at least 2 parameters, 1 given in C:\xampp\htdocs\Login\connect.php on line 32 Fatal error: Call to undefined function mysqli_result() in C:\xampp\htdocs\Login\connect.php on line 33 Code Updated: $mysqli_db = mysqli_select_db($mysqli_connect, $db_name); if(!$mysqli_db) { printf("Database not found: %s\n", $mysqli->connect_error); exit(); } $sql = "SELECT * FROM $tbl_name WHERE username='$username' AND password='$password'"; $query = mysqli_query($sql); $result = mysqli_result($query); $row = mysqli_fetch_assoc($result); Edited by Tom8001, 30 November 2014 - 12:43 PM. hello , I'm starting to use mysqli and i have few questions. is there a guide for mysqli? and how do i use this functions at mysqli ? mysql_num_rows mysql_query mysql_fetch_assoc mysql_fetch_array thanks , Mor. Hi, The following code is what I want in that it creates a menu and I can select and display a table row.
I still need to use that selection to update the "lastused". I really appreciate your help. <!DOCTYPE><html><head><title>email menu</title></head> <body><center> <form name="form" method="post" action=""> <?php $con=mysqli_connect("localhost","root","cookie","homedb"); //============== check connection if(mysqli_errno($con)) {echo "Can't Connect to mySQL:".mysqli_connect_error();} else {echo "Connected to mySQL</br>";} //This creates the drop down box echo "<select name= 'target'>"; echo '<option value="">'.'--- Select email account ---'.'</option>'; $query = mysqli_query($con,"SELECT target FROM emailtbl"); $query_display = mysqli_query($con,"SELECT * FROM emailtbl"); while($row=mysqli_fetch_array($query)) {echo "<option value='". $row['target']."'>".$row['target'] .'</option>';} echo '</select>'; ?> <input type="submit" name="submit" value="Submit"/><!-- update "lastused" using selected "target"--> </form></body></html> <!DOCTYPE><html><head><title>email menu</title></head> <body><center> <?php $con=mysqli_connect("localhost","root","cookie","homedb"); if(mysqli_errno($con)) {echo "Can't Connect to mySQL:".mysqli_connect_error();} if(isset($_POST['target'])) { $name = $_POST['target']; $fetch="SELECT target,username,password,emailused,lastused, purpose, saved FROM emailtbl WHERE target = '".$name."'"; $result = mysqli_query($con,$fetch); if(!$result) {echo "Error:".(mysqli_error($con));} $lastused = "CURDATE()"; // update "lastused" using selected "target" //display the table echo '<table border="1">'.'<tr>'.'<td bgcolor="#ccffff align="center">'. 'Email menu'. '</td>'.'</tr>'; echo '<tr>'.'<td>'.'<table border="1">'.'<tr>'.'<td bgcolor="#ccffff align="center">'.'target'.'</td>'.'<td bgcolor="#ccffff align="center">'.'username'.'</td>'.'<td bgcolor="#ccffff align="center">'.'password'.'</td>'.'<td bgcolor="#ccffff align="center">'.'emailused'.'</td>'.'<td bgcolor="#ccffff align="center">'.'lastused'.'</td>'.'<td bgcolor="#ccffff align="center">'.'purpose'. '</td>'.'<td bgcolor="#ccffff align="center">'. 'saved' .'</td>'.'</tr>'; while($data=mysqli_fetch_row($result)) {echo ("<tr><td>$data[0]</td><td>$data[1]</td><td>$data[2]</td><td>$data[3]</td><td>$data[4]</td><td>$data[5]</td><td>$data[6]</td></tr>");} echo '</table>'.'</td>'.'</tr>'.'</table>'; } ?> </body></html> Hello everyone, For two weeks now, I'm trying to get this database connection in my query. Can someone give me a solution and tell me what I've done wrong? Am I overlooking something? <?php class Mysql{ public function connect(){ $mysqli = new mysqli('localhost','root','','login'); } } class Query extends Mysql{ public function runQuery(){ $this->result = parent::connect()->query("select bla bla from bla bla"); } } $query = new Query; $query->runQuery(); ?> I dont know whether the statement is correct.....i just tried it.....and it didn't work. $stmt->bind_param('ssiiiss',$_POST['name'],$_POST['email'],$_POST['d'],$_POST['m'],$_POST['y'],$_POST['add'],$_POST['phone']); here my first two values are strings and next 2 tiny int's next is int and last 2 again strings. Ok I am trying to use mysqli instead of the usual mysql. Mysql would be outdated. With mysqli, sgl-injection is impossible if you use the "?" in those codes. I would normally use a function but I've made a simple script to find the error. I use $parameters and $sql because these are the data I need to give as parameters to the function, so I used it here too but without the function actually. Code: [Select] ini_set('display_errors',1); // 1 == aan , 0 == uit error_reporting(E_ALL | E_STRICT); # sql debug define('DEBUG_MODE',true); // true == aan, false == uit $userid = 11; $lang = 1; $newLink = "testing123"; $db_host = "localhost"; $db_gebruiker = "root"; $db_wachtwoord = ''; $db_naam = "projecteasywebsite"; $sql= "INSERT tbl_link(userid,linkcat,linksubid,linklang,linkactive,linktitle) VALUES(?, ?, ?, ?, ?, ?)"; $parameters = '"iiisis", $userid, 1, 0, $lang, 1, $newLink'; echo $parameters; $mysqli = new mysqli($db_host, $db_gebruiker, $db_wachtwoord, $db_naam); $stmt = $mysqli->prepare($sql); $stmt->bind_param($parameters); $stmt->execute(); echo "<br><br>". mysqli_connect_errno(); echo "<br><br>". mysqli_report(MYSQLI_REPORT_ERROR); $stmt->close(); $mysqli->close(); I got Wrong parameter count for mysqli_stmt::bind_param() So naturally a problem when we execute : Warning: mysqli_stmt::execute() [mysqli-stmt.execute]: (HY000/2031): No data supplied for parameters in prepared statement ($stmt->execute() Is someone using mysqli too ? I am using mysqli, OO, to connect to MySQL. I have only today started looking at this and am used to: Code: [Select] <?php $con = mysql_connect();//etc mysql_close($connection); ?> Am I right that with mysqli (OO) that I don't need to set a connection variable wither when connecting or closing?? Code: [Select] <?php mysqli::connect();//etc mysqli::close(); ?> What about with multiple databases, does mysqli keep track for me, as I am used to this: Code: [Select] <?php $con1 = mysql_connect();//db1 $con2 = mysql_connect();//db2 ?> //etc I have converted my mysql to mysqli and am working on converting some functions. My question - Can I not just convert the mysql to mysqli? This is the full code: Code: [Select] class zipcode_class { var $last_error = ""; // last error message set by this class var $last_time = 0; // last function execution time (debug info) var $units = _UNIT_MILES; // miles or kilometers var $decimals = 2; // decimal places for returned distance function get_zip_point($zip) { // This function pulls just the lattitude and longitude from the // database for a given zip code. $sql = "SELECT lat, lon from zip_code WHERE zip_code='$zip'"; $r = $mysqli->query($sql); if (!$r) { $this->last_error = mysql_error(); return false; } else { $row = mysql_fetch_array($r); mysql_free_result($r); return $row; } } function calculate_mileage($lat1, $lat2, $lon1, $lon2) { // used internally, this function actually performs that calculation to // determine the mileage between 2 points defined by lattitude and // longitude coordinates. This calculation is based on the code found // at http://www.cryptnet.net/fsp/zipdy/ // Convert lattitude/longitude (degrees) to radians for calculations $lat1 = deg2rad($lat1); $lon1 = deg2rad($lon1); $lat2 = deg2rad($lat2); $lon2 = deg2rad($lon2); // Find the deltas $delta_lat = $lat2 - $lat1; $delta_lon = $lon2 - $lon1; // Find the Great Circle distance $temp = pow(sin($delta_lat/2.0),2) + cos($lat1) * cos($lat2) * pow(sin($delta_lon/2.0),2); $distance = 3956 * 2 * atan2(sqrt($temp),sqrt(1-$temp)); return $distance; } function get_zips_in_range($zip, $range, $sort=1, $include_base) { // returns an array of the zip codes within $range of $zip. Returns // an array with keys as zip codes and values as the distance from // the zipcode defined in $zip. $this->chronometer(); // start the clock $details = $this->get_zip_point($zip); // base zip details if ($details == false) return false; // This portion of the routine calculates the minimum and maximum lat and // long within a given range. This portion of the code was written // by Jeff Bearer (http://www.jeffbearer.com). This significanly decreases // the time it takes to execute a query. My demo took 3.2 seconds in // v1.0.0 and now executes in 0.4 seconds! Greate job Jeff! // Find Max - Min Lat / Long for Radius and zero point and query // only zips in that range. $lat_range = $range/69.172; $lon_range = abs($range/(cos($details[0]) * 69.172)); $min_lat = number_format($details[0] - $lat_range, "4", ".", ""); $max_lat = number_format($details[0] + $lat_range, "4", ".", ""); $min_lon = number_format($details[1] - $lon_range, "4", ".", ""); $max_lon = number_format($details[1] + $lon_range, "4", ".", ""); $return = array(); // declared here for scope $sql = "SELECT zip_code, lat, lon FROM zip_code "; if (!$include_base) $sql .= "WHERE zip_code <> '$zip' AND "; else $sql .= "WHERE "; $sql .= "lat BETWEEN '$min_lat' AND '$max_lat' AND lon BETWEEN '$min_lon' AND '$max_lon'"; $r = mysql_query($sql); if (!$r) { // sql error $this->last_error = mysql_error(); return false; } else { while ($row = mysql_fetch_row($r)) { // loop through all 40 some thousand zip codes and determine whether // or not it's within the specified range. $dist = $this->calculate_mileage($details[0],$row[1],$details[1],$row[2]); if ($this->units == _UNIT_KILOMETERS) $dist = $dist * _M2KM_FACTOR; if ($dist <= $range) { $return[str_pad($row[0], 5, "0", STR_PAD_LEFT)] = round($dist, $this->decimals); } } mysql_free_result($r); } // sort array switch($sort) { case _ZIPS_SORT_BY_DISTANCE_ASC: asort($return); break; case _ZIPS_SORT_BY_DISTANCE_DESC: arsort($return); break; case _ZIPS_SORT_BY_ZIP_ASC: ksort($return); break; case _ZIPS_SORT_BY_ZIP_DESC: krsort($return); break; } $this->last_time = $this->chronometer(); if (empty($return)) return false; return $return; } } I have some code I used to have in mysql and now im trying to convert to mysqli and I cant seem to find out what the problem is.
<?php $username = $_SESSION['username']; // Connect to server and select databse. include "db_connect.php"; include "db_config.php"; // items tables selection $sql = mysqli_query($my_database,"SELECT * FROM items_tbl WHERE level = '$account_info[player_level]' ORDER BY rand()"); //$result = mysqli_query($my_database,$sql); // Put info into array (This Works) while($item = mysqli_fetch_assoc($sql)){ //stats $items_id['itemid'] = $item['itemid']; $items_id['Level'] = $item['Level']; $items_id['name'] = $item['name']; $items_id['min_str'] = $item['min_str']; $items_id['min_int'] = $item['min_int']; $items_id['min_dex'] = $item['min_dex']; $items_id['type'] = $item['type']; $items_id['min_dmg'] = $item['min_dmg']; $items_id['max_dmg'] = $item['max_dmg']; $items_id['phys_defense'] = $item['phys_defense']; $items_id['mag_defense'] = $item['mag_defense']; } ?>here is the error im getting: Warning: mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given Greeting all. I am brand new to the forum and I would like to ask a question regarding mysqli. I am not certain why the following code works: Code: [Select] ... $sqlCmd = "select * from usrdata"; $rs = $mysqli->query($sqlCmd); ... and the following code gives me a 500 internal error: Code: [Select] ... $sqlCmd = "select * from usrdata"; $result= dbQuery($sqlCmd); ... function dbQuery($sqlCmd){ $rt = array(); $rs = $mysqli->query($sqlCmd); while($row = $rs->fetch_assoc ()){ $rt[] = $row; } return 'records: ' . json_encode($rt); } The error occurs on the mysqli->query. Thanks for any help. Cheers! |