Eggzorcist Posted May 19, 2011 Share Posted May 19, 2011 I've been starting to play around the mysqli class and I've been having trouble using it due to various error it gives me from simple queries like this one. I'm not sure what the error is really, I've been following the php manual. Any help would be greatly appreciated. <?php $mysqli = new MySQLi('localhost', 'root', 'root', 'jaipai'); if ($mysqli->connect_errno) { echo "There was a connection error: ". $mysqli->connecterrno; } class testClass { private $db; function __construct($mysqli) { $this->db = $mysqli; } public function pageInfo() { $query = "SELECT * FROM users WHERE username = jaipai"; $results = $this->db->query($query); $result = $this->db->fetch_assoc($results); return $result['username']; } } $testClass = new testClass($mysqli); echo $testClass->pageInfo(); ?> This gives me this error: Fatal error: Call to undefined method mysqli::fetch_assoc() in /Users/JPFoster/Sites/Research & Development/Programs/Object Sandbox/DatabaseConnection.php on line 30 Just to be a little more informative I've also tried this method $results = $this->db->query($query); $result = $results->fetch_assoc(); return $result['username']; This gives me an error: Fatal error: Call to a member function fetch_assoc() on a non-object in Sites/Research & Development/Programs/Object Sandbox/DatabaseConnection.php on line 30 I'm not sure which is on the best path to go. Any help would be greatly appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/236877-using-the-mysqli-object-fetch_assoc-problem/ Share on other sites More sharing options...
DavidAM Posted May 19, 2011 Share Posted May 19, 2011 Your problem stems from the fact that the query is failing because you do not have quotes around the username. The DB Server is trying to compare the value in the column named "username" with the value in the column named "jaipai", which is (probably) NOT a column. You should always check to see if the query succeeded. In this case, $results will be false. Also, I don't think that fetch_assoc() is a method of the database object, I think it is a method of the result-set object. Of course, I have not used mysqli much, so I could be wrong. I think the correct code for that method would be more like this: public function pageInfo() { $query = "SELECT * FROM users WHERE username = 'jaipai'"; $results = $this->db->query($query); if (! $results) return false; // OR return something else, like: "*UNKNOWN USER*" $result = $results->fetch_assoc(); return $result['username']; } Quote Link to comment https://forums.phpfreaks.com/topic/236877-using-the-mysqli-object-fetch_assoc-problem/#findComment-1217711 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.