How to loop through a mysql result set

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli($servername, $username, $password, $dbname);
$conn->set_charset('utf8mb4');

$sql = "SELECT * FROM table";
$result = $conn->query($sql)->fetch_all(MYSQLI_ASSOC);

foreach ($result as $row):
?>
//Loop Content... Example:-

<li><?= $row['name']; ?></li>

<?php
endforeach;
?>

Here is a full example:

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

  1. Connect
  2. Select database
  3. Make query
  4. Cycle on the result and fetch array to get the row

If you are using MySQL versions 4.1.3 or later, it is strongly recommended that you use the mysqli extension instead [of the mysql extension that is not further developed, does not support features of MySQL 4.1+, no prepared and multiple statements, has no object-oriented interface, ...]

see mysqli-stmt.fetch for the procedural and object oriented ways to loop over a mysqli result set.


the first example that comes to my mind:

    <?php

    $link = mysql_connect(/*arguments here*/);

    $query = sprintf("select * from table");

    $result = mysql_query($query, $link);

    if ($result) {
      while($row = mysql_fetch_array($result)) {
        // do something with the $row
      }

    }
    else {
      echo mysql_error();
    }
?>