无法从准备好的声明中返回结果

时间:2013-10-22 10:51:57

标签: mysqli

经过几个小时的各种脚本示例并尝试了几乎所有我认为在寻找答案时可以远程理解的东西,我再次受到更聪明的支配。我想要做的就是从我的用户数据库表中返回一个名字。是这么难,对我来说是YEP。有人请我直截了当。 我已经对所有错误进行了排序,现在我什么也没得到,问题,我认为?,在返回结果语句中。这是我的代码:

<?php
//connect to database
$mysqli = new mysqli('localhost', 'fiona', 'imB04', 'Org_db');

// check connection
    if (mysqli_connect_errno()) {
      echo "Connect failed: " . mysqli_connect_errno(); exit();
    }

//Prepared statement, bind and execute 
    if (!$stmt = $mysqli->prepare("SELECT `name` FROM users WHERE name = ?" )) {
    echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
//bind parametres
if (!$stmt->bind_param("i", $name)) {
    echo "Binding param failed: (" . $stmt->errno . ") " . $stmt->error;
//execute query or return error
}
if (!$stmt->execute()) {
    echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
//bind result variable
if (!$stmt->bind_result($name)) {
    echo "bind result failed: (" . $stmt->errno . ") " . $stmt->error;
}
  if ($result = $mysqli->prepare("SELECT `name` FROM users WHERE name = ?")) {
 while ($row = $result->fetch_array()) 
 {
 echo $result['name'];
 }
  }

//Close statement 
      $stmt -> close();
//Close connection 
   $mysqli -> close();  

?>

1 个答案:

答案 0 :(得分:-1)

尝试使用此代码,但我认为您在错误检查方面已经超越了顶部。我可以在此选择中添加一个else来检查失败。将$ db更改为调用数据库的任何内容。

    $query = "SELECT `name` FROM `users` WHERE `name`=?";
    $stmt = $db->prepare($query);
    $stmt->bind_param('s',$name);
    $stmt->execute();
    $stmt->bind_result($name);

    if($stmt->fetch())
    {
        echo $name;
    }
    $stmt->close();

另外,为了搜索名字,我会用这个

<snip>
"WHERE CONCAT(`firstname`, ' ',`lastname`) LIKE CONCAT('%', ?, '%')";
$stmt->bind_param('s',$name);
<snip>

这是查找名字和姓氏的示例。如果你使用concat,如果他们只有名字的一部分,或者他们有名字或姓氏,那就不重要了。

相关问题