使用预处理语句mysqli获取查询结果

时间:2018-05-17 02:32:11

标签: php mysql prepared-statement

我想使用预准备语句获取查询结果,但我没有得到任何结果。

问题是我无法获取结果。有人可以展示如何使用预准备语句获取查询结果的示例吗?

这是我的代码:

    $sql = "SELECT `username` FROM `usrs` WHERE `username` = ? ";
    $statement = $this->conn->prepare($sql);

    if (!statement)
    {
        throw new Exception($statement->error);
    }

    $statement->bind_param("s",$username);
    $statement->execute();
    $statement->bind_result($user);
    while ($statement->fetch()) 
    {
        printf("%s", $user);
    }

1 个答案:

答案 0 :(得分:1)

看起来非常接近。我添加了两行。一行存储结果,另一行检查以确保您有来自查询的响应。运行它,看它是否有帮助。

$sql = "SELECT `username` FROM `usrs` WHERE `username` = ? ";
  $statement = $this->conn->prepare($sql);

  if (!statement)
  {
      throw new Exception($statement->error);
  }

  $statement->bind_param("s",$username);
  $statement->execute();
  $statement->store_result(); //<-- Added this.
  if($statement->num_rows === 0) exit('No rows');//<--Test to see if you have a result.
  $statement->bind_result($user);
  while ($statement->fetch()) 
  {
      printf("%s", $user);
  }