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 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: