I've been trying for a few days now to fix this part of my PHP code, but nothing seems to be working.
I'm basically a super-newb. Pretty much last week I decided to try and make a blog from scratch using PHP. This requires that I learn PHP. So, by following tutorials and reading sites like w3schools, I've slowly been learning applicable PHP.
Anyway, here is the part of my code I'm working on:
$query = $db->prepare("SELECT post_id, title, body, date_posted, category
FROM posts INNER JOIN categories ON
categories.category_id=posts.category_id ORDER BY
post_id desc limit $start, $per_page");
$query->execute();
$query->bind_result($post_id, $title, $body, $date_posted, $category);
$author = $db->prepare("SELECT username FROM posts INNER JOIN user ON
user.user_id=posts.user_id");
print_r( $author->error );
$author->execute();
$author->bind_result($username);
Let me explain. I have 3 database tables: posts, categories, and user. Most post information is in "posts," including category_id and user_id, but not the actual names of the category and user. I get those from the other two tables. $db uses mysqli.
The $query part of the above code works perfectly fine. The $author prepare line is where I'm having an issue. I wrote that line based on the $query prepare line that works.
But when I run the code, I get "Notice: Trying to get property of non-object." This then leads to $author->execute() not working and producing the error: "Fatal error: Call to a member function execute() on a non-object."
So again, since I'm a mega-newb, I assume the fix is something really simple that probably has to do with my ignorance of PHP. Does anyone have any idea or suggestions? Thanks in advance for the help.
The error is saying that $author is a non-object.
If $author = $db->prepare()
had executed properly it would have returned a mysqli_stmt
object. Instead it probably returned false
You can this confirm by:
echo($author); // Should be false
echo($db->error); // A string representation of your error.
Edit for posterity:
A better practice, fault tolerant implementation of a prepare() statement might be something like below, as is described here:
$stmt = $mysqli->prepare($query) or trigger_error($mysqli->error);
You should check out the docs here: http://www.php.net/manual/en/mysqli.prepare.php
Also, if you are new to PHP, I would recommend the PDO libraries instead of mysqli, they are a little easier to work with once you start fetching results.