What's with mysqli in php?
I used to code in php4 but now I switched to php5 and the following code throws the below exception. Why is that?
CODE:
$mysqli = new mysqli($CONFIG_DB_HOST,$CONFIG_DB_U开发者_如何学CSERNAME,$CONFIG_DB_PASSWORD,$CONFIG_DB_NAME);
$result = $mysqli->query("select * from temp_table where url = '" . $mysqli->real_escape_string($in_url) . "'");
$row = $result->fetch_assoc();
$out_title = $row['title'];
Exception:
Fatal error: Call to a member function fetch_assoc() on a non-object in detail.php on line 13
Looks like there is some problem with your query and as a result of that the query()
method returns false
rather than a result object
and when you call a fetch_assoc()
method on a non-object you get this error. Print the query that is being run and try to run from say phpmyadmin and see what error you get.
Also always check the return value of the query() method before you proceed:
if (!$mysqli->query("query"))
{
printf("Error: %s\n", $mysqli->error);
}
You can also check to see if your $result contains an actual result:
if ($result != false) {
$row = $result->fetch_assoc();
}else{
// do something else!
// maybe trigger_error()?
}
Also keep in mind that if your result contains more than one row you'll most likely want to run through a loop
while ($row = $result->fetch_assoc()) {
$out_title = $row['title'];
}
Doing that will also keep you from getting that error you got, because the while loop will evaluate the return value of $result->fetch_assoc() before it assigns it to $row, if it returns false $row never gets set, and the while loop doesn't run.
You may:
<?php
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
//more things
}
}
精彩评论