inner join wont work with mysqli prepared statemen

2019-08-22 04:40发布

问题:

I can't seem to get this statement or statements alike to work with prepared queries, the code works just fine below:

$DBH = getDBH();
    $stmt = $DBH->prepare("SELECT a.id, a.title, a.photo FROM tag t INNER JOIN tag_reference atx ON t.tag_id = atx.tag_id
        INNER JOIN articles a
            ON atx.article_id = a.id
    WHERE t.tag_name = 'example'");
    $stmt->execute();
    $stmt->bind_result($id,$title,$photo);
    $stmt->fetch();

but when I change t.tag_name = '?' it gives me an error that the amount of parameters do not match. This is the statement that does not work.

$DBH = getDBH();
    $stmt = $DBH->prepare("SELECT a.id, a.title, a.photo FROM tag t INNER JOIN tag_reference atx ON t.tag_id = atx.tag_id
        INNER JOIN articles a
            ON atx.article_id = a.id
    WHERE t.tag_name = '?'");
        $stmt->bind_param('s',$example);
    $stmt->execute();
    $stmt->bind_result($id,$title,$photo);
    $stmt->fetch();

Can anyone please help?

回答1:

The placeholder ? does not work if enclosed in single quotes. In this case the SQL tokenizer will catch it as literal string.

Change it to:

     WHERE t.tag_name = ? ");


回答2:

When using placeholders, do you need to use quotes? Most placeholder languages I've used don't.

WHERE t.tag_name = ?"