1

Based on this answer : https://stackoverflow.com/a/14671645/3696490

I have the following php code to get all rows from a database, and print them

                <?php
                //$con =mysqli_connect (...) ; // my DB info here
                $stmt = $con->prepare('SELECT id, username, email FROM accounts');
                
                $stmt->execute();

                $stmt->bind_result($id, $user, $email,$isadmin);
                
                
                while ($stmt->fetch()) { 

                        
                    echo "
                    <tr>
                        <td>$user</td>
                        <td>$email</td>
                        <td>$id</td>
                    </tr>";
                }
                $stmt->close();

This code works perfectly, but I was checking more examples today and I noticed in tutorials they always use stmt->get_result()

Can someone please explain how/why the above code works fine without get/store ?

Thanks

user206904
  • 504
  • 4
  • 16
  • 2
    basically you need get_result() because result->fetch_assoc is wayyyyy more usable than this bind_result mess – Your Common Sense Mar 23 '22 at 14:46
  • Note that you should never mix SQL and HTML in the same file and should never echo HTML in PHP – Your Common Sense Mar 23 '22 at 14:47
  • @YourCommonSense do you mind detailing a bit more? I am not sure I understand... Thanks – user206904 Mar 23 '22 at 14:53
  • detailed on what? think this text would do https://phpdelusions.net/basic_principles_of_web_programming#templates – Your Common Sense Mar 23 '22 at 15:04
  • I mean, when you never output HTML directly from SQL query, you need to get an array, not separate variables. which makes bind_result extremely inconvenient – Your Common Sense Mar 23 '22 at 15:05
  • The `bind_result` result way is used when you want to have unbuffered results. You don't store or get them, but instead you ask the MySQL server for each row one by one, i.e. fetch. The field values are then assigned to the variables you bound. It's not a very easy way of reading the results, which is why tutorials recommend `get_result()` that can then be used with `fetch_assoc()` or `fetch_all()` methods. – Dharman Mar 23 '22 at 16:28

0 Answers0