我有这个代码块,应该用于在登录时验证用户。如果我尝试提供数据库中存在的电子邮件地址和密码,我会在$ loginerror中收到错误消息。我没有得到任何错误,但我的代码似乎没有得到任何结果集,因为当我尝试回显$stmt->num_rows
时它打印出来0.请问我做错了什么?
这是代码块:
<?php
if(isset($_POST['signin'])){
require_once "logincheck.php";
$signin_email=$_POST['signin_email'];
$signin_password=$_POST['signin_password'];
if($valid){
require_once 'scripts/connect_to_mysql.php';
$sql ="SELECT First_name, Last_name FROM customer WHERE Email=? AND Password=?";
$stmt=$conn->prepare($sql);//preparing the statement
if(!$stmt){
echo "Unable to prepare: ".$conn->errno. " " .$conn->error;
}
//executing the statement
//$date=date('d m Y h:i:s');
if(!$stmt->bind_param('ss', $signin_email, $signin_password)){//bind parameters to sql statement. i=integer, s=string, b=blob, d=double
echo "Binding parameters failed: ".$stmt->errno. " " . $stmt->error;
}
if(!$stmt->execute()){//executing the statement
echo "Statement Execution failed: ". $stmt->error;
}
if(!$stmt->bind_result($firstname,$lastname)){// used to bind variables to a prepared statement for result storage
echo "Unable to bind results to variables: ".$stmt->error;
}
//echo $stmt->num_rows;
if($stmt->num_rows===1){//to check if username and password actually exists
while($stmt->fetch()){
$user=$firstname. " ". $lastname;
echo $user;
}
$_SESSION['user']=$user;
header('location:logintest.php');
exit();
}
else{
$loginerror= "Invalid Email address/Password. Please try again";
}
$stmt->close();//closing the prepared statement
$conn->close();//closing the connection
}
}
?>
答案 0 :(得分:0)
好的,我可以通过在代码中添加$stmt->store_result()
来解决这个问题。所以现在我有,
if(!$stmt->bind_result($firstname,$lastname)){// used to bind variables to a prepared statement for result storage
echo "Unable to bind results to variables: ".$stmt->error;
}
$stmt->store_result();
if($stmt->num_rows===1){//to check if username and password actually exists
while($stmt->fetch()){
$user=$firstname. " ". $lastname;
echo $user;
}
取代:
if(!$stmt->bind_result($firstname,$lastname)){// used to bind variables to a prepared statement for result storage
echo "Unable to bind results to variables: ".$stmt->error;
}
if($stmt->num_rows===1){//to check if username and password actually exists
while($stmt->fetch()){
$user=$firstname. " ". $lastname;
echo $user;
}
根据PHP Manual here,您需要为store_result()
添加num_rows
才能让{{1}}工作。
答案 1 :(得分:-1)
如果您使用的是MySQL,PDOStatement :: rowCount()将返回结果集中的行数。
对于其他数据库/ MySQL,您可以
$rows = $stmt->fetchAll();
$rowCount = count($rows);