Search code examples
phpmysqlsqlphp-8

Unable to return array from SQL, only returning mysqli_stmt


I've been doing SQL for over a year now, and have became completely stuck. For some reason, i'm not able to return any values from this table as I get the error

mysqli_fetch_array(): Argument #1 ($result) must be of type mysqli_result, mysqli_stmt given

I'm completely floored as to why this is happening, as i've used these kind of queries in the past The code i'm using is

  $user = "testuser";
  $q = $conn->prepare("SELECT * FROM users WHERE username = ?");
  $q->bind_param("s", $user);
  $q->execute();
  while($row = mysqli_fetch_array($q))
      var_dump($row);

If I do var_dump($q), then I get an object object(mysqli_stmt)#3 (10) with no errors and the correct amount of fields. I'm just not able to read anything from this for some reason.

Thanks!


Solution

  • You need to call a get_result() before you can fetch your data

      $user = "testuser";
      $stmt = $conn->prepare("SELECT * FROM users WHERE username = ?");
      $stmt->bind_param("s", $user);
      $stmt->execute();
      $result = $stmt->get_result();
      while($row = $result->fetch_assoc()) {
          var_dump($row);
      }
    

    PS. better to use fetch_assoc() instead of fetch_array()