$sql = "SELECT topicid FROM posttopic WHERE $id = :postid";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':postid', $id);
$stmt->execute();
while ($topic = $stmt->fetch(PDO::FETCH_ASSOC)) {
$topicid = $topic['topicid'];
$sql = "SELECT name FROM topic WHERE $topicid = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $topicid);
echo "<p>SQL: ".$sql."</p>";
$stmt->execute();
}
The first SELECT works fine. It’s the second one that throws an exception.
I echo out the SQL statement and get…
SQL: SELECT name FROM topic WHERE 1 = :id
However, after the error is thrown, I get a SQL statement looking like…
SQL: SELECT name FROM topic WHERE = :id
Here’s the obvious error message…
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘= NULL’ at line 1’
I guess I’m trying to figure out how the $topicid value is getting dropped.
While it might look like you have wasted time on this, you have actually learned something the “hard way” and you will never forget it.
On your code, if your using prepared statement, why do you create the statement over and over again? By doing that you dont take advantage of the prepare statement at all. You can move the statement outside the loop and keep the variable assignment and execution inside the loop.
Though, you can put your two queries as a linked one as well. Making the multiple secondary queries redundant.
$sql = "SELECT topicid FROM posttopic WHERE $id = :postid";
$topics = $pdo->prepare($sql);
$topics->bindParam(':postid', $id);
$topics->execute();
while ($topic = $topics->fetch(PDO::FETCH_ASSOC)) {
$topicid = $topic['topicid'];
$sql = "SELECT name FROM topic WHERE $topicid = :id";
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':id', $topicid);
$stmt->execute();
}
Now that I see what the change needed to be, it makes sense. $stmt is being used as part of the fetch so I can’t redefine what $stmt means while that is happening.
Nothing looks to be null. The name value is actually correct, so I’m curious how the dump is getting the correct value, but yet somehow the code still gives the exception.