Gnahzllib
Gnahzllib

Reputation: 101

procedural style and object oriented style

I'm kind of confuse why that when I change from procedural style into object-oriented style, the while loop is fine ?

This is the php block on the top of my script:

 $object = new mysqli('localhost', 'readmode', 'p@5sW0rd', 'practices');
 $sql = 'SELECT * FROM paintings';
 $result = $object->query($sql);
 if ($object->connect_error) {
     $error = $object->connect_error;
 } else {
     $num_rows = mysqli_num_rows (mysqli_query($object, $sql)); 
 }

This is the php code inside my html:

 <?php if (isset($error)) {
     echo "<p>$error</p>";
 } else { ?>
     <pre><?php while ($rowinfo = mysqli_fetch_assoc($result)) { 
         print_r ($rowinfo);
     } ?></pre>
 <?php } ?>

When I use $object->query($sql) instead of $result, the loop becomes infinite. (I'm jumping back and forth with the procedural style and the object-oriented style because I'm practicing with it)

Upvotes: 0

Views: 254

Answers (1)

Your Common Sense
Your Common Sense

Reputation: 157880

famous for not knowing how to asking questions

Sad but true.

If some of your code is not working, it's better to post this very code instead of writing a long literary explanation.

When you're making it

while ($rowinfo = mysqli_fetch_assoc($object->query($sql)))

it indeed makes an infinite loop, because you are making your SQL query run over and over.

The problem has nothing to do with object syntax, it will remain the same with procedural as well. You are just supposed to use the result in stead of calling query again.

In essence, you have to run your query **only once. **
Which makes your other code snippet wrong as well. It should be

$object = new mysqli('localhost', 'readmode', 'p@5sW0rd', 'practices');
 $sql = 'SELECT * FROM paintings';
 $result = $object->query($sql);
 if ($object->connect_error) {
     $error = $object->connect_error;
 } else {
     $num_rows = mysqli_num_rows($result); 
 }

otherwise it will run your query twice.

Upvotes: 0

Related Questions