小编典典

预处理语句适用于INSERT,但不适用于SELECT

sql

编辑:解决了,请看下面, 但仍然不知道我是怎么做的才能使它起作用:)

好吧,我现在被困住了。我有桌子users

ID int PRIMARY AUTO_INCREMENT
EMAIL varchar(60)
NICK varchar(60)
//...

如果我做:

<?php
$email = $_POST["mai"];
$nickname = $_POST["nck"];
$mysqli = new mysqli($db_host, $db_username, $db_password, $database);
$prepared_statement = "INSERT INTO users VALUES(?,?,?)";
if ($stmt = $mysqli->prepare($prepared_statement)) {
 $id = "";
 $stmt->bind_param("iss",$id,$email,$nickname); 
 $stmt->execute();
}
?>

它每一次都有效。但是,如果我对select执行相同操作:

<?php
 $previous_entries = new mysqli($db_host, $db_username, $db_password, $database);
 $check = $previous_entries->prepare("SELECT ID,NICK FROM users WHERE EMAIL=?;");
 $check->bind_param("s",$email);
 $check->execute();
 $check->bind_result($maybe_id,$maybe_got_something);

  while ($check->fetch()) { //here was typo, but fixed now 
    if ($maybe_got_something==$nickname){
     echo "Hooray!";
    }
  }

?>

我从未见过“万岁!”

但是,如果我这样更改它:

$previous_entries = new mysqli($db_host, $db_username, $db_password, $database);
$prepared_statement = "SELECT ID,NICK FROM users WHERE EMAIL=";
$prepared_statement .=$email;
$result = $previous_entries->query($prepared_statement);
while ($row = $result->fetch_array()){
  if ($row["NICK"]==$nickname){
     echo "Hooray!";
    }
}

那一切都很好。

我在准备好的陈述中犯了一个可怕的错误。但是我真的找不到它…我在这里做错了什么?

编辑:更新了脚本以纠正错误的拼写错误,并添加了这两行:

echo "maybeid: ".. $maybe_id;
echo "maybenick:". $maybe_got_something;

页面与此相呼应:

  maybeid: maybenick:

编辑:工作代码 尝试对其进行调试时,我明白了这一点:

$previous_entries = new mysqli($db_host, $db_username, $db_password, $database);
$check = $previous_entries->prepare("SELECT ID,NICK FROM users WHERE EMAIL=?;");
$check->bind_param("s",$email);
$check->execute();
$check->bind_result($maybeid,$maybenick);
echo "maybeid: ".$maybeid;
echo "maybenick:". $maybenick;
// got rid of the if statement
  while ($check->fetch()) {
    echo "maybeid: ".$maybeid;
    echo "maybenick:". $maybenick;
    if ($maybenick==$nickname){

     echo "Hooray!";
    }
  }

但是…为什么要担心呢?:)


阅读 217

收藏
2021-05-30

共1个答案

小编典典

尝试以下操作(使用从prepare返回的语句对象):

<?php
 $previous_entries = new mysqli($db_host, $db_username, $db_password, $database);
 $check = $previous_entries->prepare("SELECT ID,NICK FROM users WHERE EMAIL=?;");
 $check->bind_param("s",$email);
 $check->execute();
 $check->bind_result($maybe_id,$maybe_got_something);
 if($check->num_rows > 0){
  while ($check->fetch()) {
    if ($maybe_got_something==$nickname){
     echo "Hooray!";
    }
  } 
}
?>
2021-05-30