Adam Adam - 1 year ago 72
HTML Question

Prepared Statement Results to Fill HTML table with MySQL Table Fields

I'm trying to fill an HTML table with user information like this:

$mysqli = mysqli_connect($host, $username, $password, $db);
$query = "SELECT * from `users`";
$stmt = $mysqli->prepare($query);
$res = $stmt->get_result();
$data = $res->fetch_all();

foreach ($data as $row)
echo "<tr><td>" . $row['username'] . "</td><td>" . $row['email'] . "</td></tr>";

It seems the array indices are empty, however, because it results in a number of blank HTML table rows equal to the number of users in the MySQL table.

If I bind_param to the $stmt like so:

$query = "SELECT * from `users` WHERE userId = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("i", $userId);
$res = $stmt->get_result();
$data = $res->fetch_all();

There are no rows created at all in the HTML table, which leads me to believe that the array is empty.

I've gotten this far using information from this answer:

SELECT * from SQL table using prepared statement

I suppose my issue is in the prepare() parameter, $query. I can't seem to figure out exactly what it is, though.

Answer Source


$data = $res->fetch_all();


$data = $res->fetch_all(MYSQLI_ASSOC);

This way you will get associative results (e.g. $row['username'] will work) instead of ordinal results (e.g. $row[1]).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download