PHP MySQLi prepared statement select multiple rows

PHP MySQLi prepared statement select multiple rows

In this post, i will tell you how to use MySQLi prepared statement to select or fetch multiple rows.

As you know very well that by using MySQLi prepared statements we make our database query more secure to normal database query.

If you are using query as procedural way then you really should use prepared statements.

  1. <?php
  2. function getData()
  3. {
  4. $parameters = array();
  5. $arr_results = array();
  6. $db = new mysqli('localhost', 'root', '', 'database') or die('Database connection failed');
  7. $stmt = $db->prepare('SELECT name,details FROM products') or die('Something wrong with prepare query');
  8. $stmt->execute();
  9. $meta = $stmt->result_metadata();
  10. while ( $rows = $meta->fetch_field() ) {
  11. $parameters[] = &$row[$rows->name];
  12. }
  13. call_user_func_array(array($stmt, 'bind_result'), $parameters);
  14. while ( $stmt->fetch() ) {
  15. $x = array();
  16. foreach( $row as $key => $val ) {
  17. $x[$key] = $val;
  18. }
  19. $arr_results[] = $x;
  20. }
  21. return $arr_results;
  22. }
  23. $arr_results = getData();
  24. ?>
  25. <table>
  26. <tr>
  27. <th>Name</th>
  28. <th>Details</th>
  29. </tr>
  30. <?php foreach ($arr_results as $row) : ?>
  31. <tr>
  32. <td><?php echo $row['name']; ?></td>
  33. <td><?php echo $row['details']; ?></td>
  34. </tr>
  35. <?php endforeach; ?>
  36. </table>

SELECT COUNT Total records of a table

Sometime you need to know the total number of records of a table then you can get the total number of records by using this query.

  1. <?php
  2. $db = new mysqli('localhost','root','','database_name');
  3. if ($db->connect_error) {
  4. die('Error : ('. $db->connect_errno .') '. $db->connect_error);
  5. }
  6. $results = $db->query("SELECT COUNT(*) FROM products");
  7. $total_records = $results->fetch_row();
  8. $db->close();
  9. ?>
SELECT Multiple Records as Array OOP Method

fetch_array() method return an array response for both numeric key and associative string.

If you are comparing from fetch_array() vs fetch_assoc() then i always suggest you to use fetch_array() because you will never want to access records by index number if you know column name.

  1. <?php
  2. $db = new mysqli('host','username','password','database');
  3. // if connection failed
  4. if ($db->connect_error) {
  5. die('Error : ('. $db->connect_errno .') '. $db->connect_error);
  6. }
  7. //Select Query
  8. $results = $db->query("SELECT id, name, details FROM products");
  9. echo '<table border="1">';
  10. while($row = $results->fetch_array()) {
  11. echo '<tr>';
  12. echo '<td>'.$row["id"].'</td>';
  13. echo '<td>'.$row["name"].'</td>';
  14. echo '<td>'.$row["details"].'</td>';
  15. echo '</tr>';
  16. }
  17. echo '</table>';
  18. // close connection
  19. $db->close();
  20. ?>

Phone: (+91) 8800417876
Noida, 201301