简体   繁体   English

PHP PDO查询不能与Vars一起使用?

[英]PHP PDO Query Not Working With Vars?

I'm a little confused here. 我在这里有点困惑。 I've got the following code: 我有以下代码:

class Users {
    function count_matched_rows($needle, $haystack){
        global $userdb;

        $query = $userdb->prepare("SELECT COUNT(*) FROM `users` WHERE ? = ?");
        $query->execute(array($haystack, $needle));

        return $query->fetchColumn();
    }
}

$users = new Users();
print_r($users->count_matched_rows("jeremyfifty9", "username"));

Which prints 0 with an expected value of 1. So I changed it to this: 它将打印0,预期值为1。因此我将其更改为:

class Users {
    function count_matched_rows($needle, $haystack){
        global $userdb;

        $query = $userdb->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = 'jeremyfifty9'");
        $query->execute(array($haystack, $needle));

        return $query->fetchColumn();
    }
}

$users = new Users();
print_r($users->count_matched_rows("jeremyfifty9", "username"));

Which prints 1 as expected. 哪个按预期打印1。 Does anybody know why the first code prints 0 but the second prints 1? 有人知道为什么第一个代码打印0却第二个代码打印1吗?

(BTW - I'm trying to get this to simulate mysql_num_rows ) (顺便说一句-我试图mysql_num_rows模拟mysql_num_rows

You can't use a variable for the column name. 您不能使用变量作为列名。 You can only use it for the column value. 您只能将其用作列值。

The way you've done it, you're selecting all records where the string value of $haystack equals the string value of $needle . 完成此操作的方式是,选择所有记录,其中$haystack的字符串值等于$needle的字符串值。 This will almost never be true. 这几乎永远不会是真的。 In the event that it is true, you it will just return all the rows in the table. 如果为真,则只返回表中的所有行。 Regardless, it is certainly not what you intended, and hopefully explains why it returns 0 results. 无论如何,它肯定不是您想要的,并希望解释为什么它返回0个结果。

You cannot use a placeholder / variable for the variable name, only for the value. 您不能将占位符/变量用于变量名,而只能用于值。

You could just send the variable name and hard-code username in the query. 您可以只在查询中发送变量名和硬编码用户名。

An alternative would be to check the variable name against a whitelist and use a valid name as a variable directly in the query: 一种替代方法是对照白名单检查变量名称,然后在查询中直接使用有效名称作为变量:

$whitelist = array('username', ....);    // add all valid column names

// check for variable in whitelist
if (in_array($haystack, $whitelist))
{
  $query = $userdb->prepare("SELECT COUNT(*) FROM `users` WHERE `$haystack` = ?");
  $query->execute(array($needle));
  // etc.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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