我在PHP中实现了以下代码:
function attemptDBConnection($shouldRedirect){
$con=mysqli_connect("localhost","root","root","mydb");
if ($con->connect_errno && shouldRedirect)
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
header("Location: ./errorPages/nodbconnection.html");
}
return $con;
}
function isAlreadyRegistered($con){
$email=$_POST["email"];
$testSelectUser=$con->stmt_init();
$testSelectUser->prepare("SELECT * from User WHERE email=?;");
$testSelectUser->bind_param("s",$email);
$testSelectUser->execute();
$resultUser=$testSelectUser->get_result();
$rowsUser=mysqli_num_rows($resultUser);
return $rowsUser>0;
}
$con=attemptDBConnection(true);
if(isAlreadyRegistered($con)){
header("Location: ./errorPages/alreadyregistered.html");
mysqli_close($con);
exit;
}
以下事情正在发生:当调用attemptDBConnection时,mysqli_connect执行正常并且没有为$ con设置错误,此时$ con> affected_rows为0. $ con> connect_errno为零所以if是从不输入,但在条件设置后,$ con> affected_rows设置为-1 dunno为什么!
然后返回$ con。
执行isAlreadyRegistered函数时,执行调用返回true,但$ testUserSelect-> affected_rows设置为-1,但errno为0。下一次调用get_result()永远不会返回。
可能导致这种情况发生的原因是什么?我做错了什么?
PHP对我来说是一个新手,我一直无法弄清楚这里发生了什么。 谢谢。
编辑:
我做过的一些测试:如果我为此替换了isAlreadyRegistered()函数:
function isAlreadyRegistered($con){
$email=$_POST["email"];
$testSelectUser=$con->stmt_init();
$testSelectUser->prepare("SELECT * from User WHERE email='myemail@gmail.com';");
$testSelectUser->execute();
$resultUser=$testSelectUser->get_result();
$rowsUser=mysqli_num_rows($resultUser);
return $rowsUser>0;
}
然后我得到相同的结果。
如果我改为:
function isAlreadyRegistered($con){
$email=$_POST["email"];
$testSelectDoc="SELECT * from ask2doc.Medico WHERE email='myemail@gmail.com';";
$resultDoc=mysqli_query($con,$testSelectDoc);
$rowsDoc=mysqli_num_rows ($resultDoc );
return $rowsDoc>0;
}
然后它有效。知道为什么吗?
答案 0 :(得分:0)
根据mysqli_affected_rows -1的文档,表示上次查询中出现错误。
检查$testSelectUser->error
,但您使用的查询可能是错误的。
答案 1 :(得分:0)
尝试这个快速代码(未测试我希望它有效..):)
function isAlreadyRegistered($con){
$email= !empty($_POST["email"]) ? $_POST["email"] : '';
$testSelectUser=$con->stmt_init();
$testSelectUser->prepare("SELECT * from User WHERE email=?;");
$testSelectUser->bind_param("s",$email);
$testSelectUser->execute();
$testSelectUser->store_result();
return $testSelectUser->num_rows > 0;
}