PHP prepared statements - check if a value already exists

左心房为你撑大大i 提交于 2020-01-11 07:29:32

问题


I am trying to do a check on a value (email), to determine if it already exist in the db. This should be done using prepared statements. What is the best way for doing this? My solution is this (which is wrong):

$mysqli = connectToDB();
$getEmail = $mysqli->prepare('SELECT * FROM users WHERE email=?') or die('Couldn\'t check the email');
$getEmail->bind_param('s', $email);
$getEmail->execute();
$countRows = $getEmail->num_rows;
print $countRows;

It always prints out 0 even though the email aready exists in the db.


回答1:


It seems that you have an issue regarding unbuffered result. You should use store_result:

$getEmail->execute();
$getEmail->store_result();
$countRows = $getEmail->num_rows;



回答2:


You need to call $getEmail->store_result();

$mysqli = connectToDB();
$getEmail = $mysqli->prepare('SELECT * FROM users WHERE email=?') or die('Couldn\'t check the email');
$getEmail->bind_param('s', $email);
$getEmail->execute();
$getEmail->store_result();
$countRows = $getEmail->num_rows;
print $countRows;


来源:https://stackoverflow.com/questions/19135035/php-prepared-statements-check-if-a-value-already-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!