Sangam254
Sangam254

Reputation: 3483

$mysqli->fetch_object($result) not working

I am learning mysqli.

I am trying to fetch data from a table "tbllogin".

      //DATABASE CONNECTION

      $hostname="p:localhost";
      $database="dbLogin";
      $username="user1";
      $password="pwd1";



      $mysqli = new mysqli($hostname, $username, $password,$database);

      if(mysqli_connect_errno()){

       echo mysqli_connect_error();

      }

      // Create Query
      $query = "SELECT * FROM tbllogin";


      // Escape Query

      $query = $mysqli->real_escape_string($query);
      echo $query;

      // Execute Query

      if($result = $mysqli->query($query)){

          print_r($result);

          while($row = $mysqli->fetch_object($result)){

              echo $row->column;

          }

          //Free result set
          $result->close();

      }



      ?>

But $mysqli->fetch_object($result) is not working. The if statement containing $mysqli->fetch_object($result) does not execute. I cannot identify if there is any error.

Please help. Also, suggest whether mysqli procedural form is better or object-oriented form?

Thanks in advance.

Upvotes: 5

Views: 29093

Answers (2)

Francis Bailey
Francis Bailey

Reputation: 63

Try this:

if($result = $mysqli->query($query)){

      print_r($result);

      while($row = $result->fetch_object($result)){

       //do something

      }
 }

You need to chain the commands together.

Upvotes: 1

Terry Seidler
Terry Seidler

Reputation: 2043

Shouldn't that be $result->fetch_object() ?

http://php.net/manual/en/mysqli-result.fetch-object.php

From Example 1:

if ($result = $mysqli->query($query)) {

    /* fetch object array */
    while ($obj = $result->fetch_object()) {
        printf ("%s (%s)\n", $obj->Name, $obj->CountryCode);
    }

According to the answers on this stackoverflow page, there is not much of a difference between the two.

Upvotes: 12

Related Questions