简体   繁体   中英

bindParam PDO PHP

I am having a problem with binding param or value, does anybody knows what wrong? If i change ? to area it works :-$

$item = 'area';
$query = dbConnectionPDO::getConnect()->prepare( ' SELECT * FROM  ? ' );
$query->bindParam(1, $item, PDO::PARAM_STR);
$query->execute();

while($resultId = $query->fetch(PDO::FETCH_ASSOC)){
    ////
}

Is this a good solution? It works!

$select = 'select * from ' . $item . ' left join ' . $TableName . ' ';

$query = dbConnectionPDO::getConnect()->prepare("$select ON :three = :four");
$query->bindValue(':three', $three, PDO::PARAM_STR);
$query->bindValue(':four', $four, PDO::PARAM_STR);
$query->execute();

while($resultId = $query->fetch(PDO::FETCH_ASSOC)){
    ////
}

You're trying to bind a table name, not a parameter. I'm not sure you can actually do that.

bindParam works by binding question-mark holders or named parmeters , not a table name.

$sth = $dbh->prepare('SELECT name, colour, calories
    FROM fruit
    WHERE calories < ? AND colour = ?');
$sth->bindParam(1, $calories, PDO::PARAM_INT);
$sth->bindParam(2, $colour, PDO::PARAM_STR, 12);
$sth->execute();

If you're just looking into placeholder "replacement" you can just use sprintf, but be careful since if you'll be doing anything fishy or stupid (like accepting the table name from an external source), it might be leaky.

For example:

$theQ = "SELECT * FROM `%s` LEFT JOIN `%s` ON `%s` = `%s`";
$runQ = sprintf($theQ, 'one', 'two', 'three', 'four');

You need to provide a valid SQL statement where only literals are parametrized. Even if the database driver is dumb enough to accept the query, you'll end up executing something like:

SELECT * FROM 'area'

... which is obviously not what you intended.

您不能参数化表名称,只能参数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM