简体   繁体   中英

get results of query using prepared statements mysqli

I would like to get the results of a query using prepared statements but I don't get anything.

The problem is I'm not able to fetch my results. Can some one show an example how to get results of query using prepared statements?

Here is my code:

    $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);
    }

Looks pretty close. I added two lines. One line stores the result and the other is a check to make sure you had a response from the query. Run it and see if it helps.

$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);
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM