简体   繁体   中英

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:

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. Does anybody know why the first code prints 0 but the second prints 1?

(BTW - I'm trying to get this to simulate 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 . 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.

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.
}

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