Reputation: 65
Im having this query:
$query = $db->query("SELECT
posts.post_topic_id,
posts.post_content,
posts.post_id,
posts.post_date,
posts.post_by,
posts.post_votes_total,
posts.post_suggested_amount,
posts.post_accepted,
posts.post_last_edited,
posts.post_edit_sum,
users.user_id,
users.username
FROM
posts
JOIN
users
ON
posts.post_by = users.user_id
WHERE
posts.post_topic_id = :topic_id
ORDER BY
:sort
LIMIT :start , :per_page
");
$query->bindParam(':topic_id', $topic_id, PDO::PARAM_INT);
$query->bindParam(':sort', $sort, PDO::PARAM_STR);
$query->bindParam(':start', $start, PDO::PARAM_INT);
$query->bindParam(':per_page', $per_page, PDO::PARAM_INT);
$query->execute();
But it wont execute and give me and error instead:
exception 'PDOException' with message 'SQLSTATE[42000]: Syntax error or access violation: 1064 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 ':topic_id ORDER BY posts.post_id ASC ' at line 25' in C:\htdocs\lr\topic.php:577 Stack trace: #0 C:\htdocs\lr\topic.php(577): PDO->query('SELECT???? ...') #1 {main}
If I don't prepare the statements, and I use the normal variables, the query executes just fine.
What's my mistake?
Upvotes: 0
Views: 244
Reputation: 74096
You mix up methods for prepared statements and simple queries. The bindParam()
method just relates to prepared statements. On its own, the query()
method tries to execute the given query immediately, which fails, because the parameters have not been substituted.
To solve this, just change to prepared statements all along by using
$query = $db->prepare("SELECT ... " );
and then execute after binding all variables
$query->exec();
Upvotes: 4