带有bind的PHP select语句

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (99)

我正在尝试通过PHP验证注册表单,使用预处理语句和绑定参数,如下所示:

$email = $_POST['email'];
$password = $_POST['password']; 
$selectStatement = "SELECT id FROM users WHERE email = ? ";
$stmts = mysqli_prepare($dbc, $selectStatement);
mysqli_stmt_bind_param($stmts,'s', $email);
mysqli_stmt_execute($stmts);
$count = mysqli_stmt_num_rows($stmts);

if (!$stmts){
    die('mysqli error: '.mysqli_error($dbc));
}
while($row = mysqli_stmt_fetch($stmts)){
    if($row != null){   
        echo('User already registered!');
    }
    }else{  
        $insertQuery = "INSERT INTO users(email, password) VALUES(?, ?)";
        $stmtI = mysqli_prepare($dbc, $insertQuery); 
        mysqli_stmt_bind_param($stmtI, "ss", $email, $password);
        mysqli_stmt_execute($stmtI);
        echo('Registration completed!');
}
}
mysqli_stmt_close($stmts);  
mysqli_stmt_close($stmtI);
mysqli_close($dbc); 

但是当在数据库中找不到用户时,它应该在else分支上,但是,显然它没有到达那里,甚至在while循环中也没有。我究竟做错了什么?

提问于
用户回答回答于

你的代码错了......在

}
}else{

只写

}else{

尝试这个

$email = $_POST['email'];
$password = $_POST['password'];
$selectStatement = "SELECT id FROM users WHERE email = ? ";
$stmts = mysqli_prepare($dbc, $selectStatement);
mysqli_stmt_bind_param($stmts,'s', $email);
mysqli_stmt_execute($stmts);
$count = mysqli_stmt_num_rows($stmts);

if (!$stmts){
    die('mysqli error: '.mysqli_error($dbc));
 }
while($row = mysqli_stmt_fetch($stmts)){
if($count == 1){
    echo('User already registered!');
}else{
    $insertQuery = "INSERT INTO users(email, password) VALUES(?, ?)";
    $stmtI = mysqli_prepare($dbc, $insertQuery);
    mysqli_stmt_bind_param($stmtI, "ss", $email, $password);
    mysqli_stmt_execute($stmtI);
    echo('Registration completed!');
    }
}
mysqli_stmt_close($stmts);
mysqli_stmt_close($stmtI);
mysqli_close($dbc);
用户回答回答于

while循环仅在从数据库中找到记录时执行(mysqli_stmt_fetch($ stmts))

你必须像这样改变你的代码

$email = $_POST['email']; 
$password = $_POST['password']; $selectStatement = "SELECT id FROM users WHERE email = ? "; 
$stmts = mysqli_prepare($dbc, $selectStatement);
mysqli_stmt_bind_param($stmts,'s', $email);
mysqli_stmt_execute($stmts);
$count = mysqli_stmt_num_rows($stmts);
if (!$stmts){ die('mysqli error: '.mysqli_error($dbc));
}
    if($count){
            echo('User already registered!');
    }else{
            $insertQuery = "INSERT INTO users(email, password) VALUES(?, ?)";
            $stmtI = mysqli_prepare($dbc, $insertQuery); 
            mysqli_stmt_bind_param($stmtI, "ss", $email, $password);
            mysqli_stmt_execute($stmtI);
            echo('Registration completed!');
    }

扫码关注云+社区

领取腾讯云代金券