Reputation: 387
I am new to mysqli and I am trying to output a simple query into an HTML table. I get three blank cells returned but nothing inside of them.
I tried looking around here to find this and maybe my search skills aren't up to par, so either nobody else got stuck here, or I can't search for squat! Anyway, this is my code:
<?php
$mysqli = new mysqli("localhost", "webuser", "mysecretpassword", "userdb");
/* check connection */
if ($mysqli->connect_errno)
{
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
/* Select queries return a resultset */
if ( $result = $mysqli->query("select first_name, last_name, last_activity_date from users order by first_name" ) )
{
$finfo = $result->fetch_fields();
foreach ( $finfo as $val )
{
echo "<tr>\n";
echo "<td>$val->first_name</td>\n";
echo "<td>$val->last_name</td>\n";
echo "<td>$val->last_activity_date</td>\n";
echo "</tr>\n";
}
$result->close();
}
$mysqli->close();
?>
While I have seen other examples using printf() I am not familiar with its syntax since I am not used to C style printf since I had used the echo style previously on my old database transactions.
Any help is greatly appreciated here. Thanks!
Upvotes: 1
Views: 1588
Reputation: 11096
It's not about the foreach or while loop, fetch_fields does not return the query result but the meta data about the columns of the query result (such as name, length, type etc)
You should also get a PHP warning as well on $val->first_name
since this object member isn't defined.
Upvotes: 0
Reputation: 387
if ( $result = $mysqli->query("select first_name, last_name, last_activity_date from worker order by first_name" ) )
{
while ( $val = $result->fetch_object() )
{
echo "<tr>\n";
echo "<td>" . $val->first_name . "</td>\n";
echo "<td>" . $val->last_name . "</td>\n";
echo "<td>" . $val->last_activity_date . "</td>\n";
echo "</tr>\n";
}
$result->close();
}
Upvotes: 2
Reputation: 30488
Try this
foreach ( $finfo as $val )
{
echo "<tr>\n";
echo "<td>" . $val->first_name . "</td>\n";
echo "<td>" . $val->last_name . "</td>\n";
echo "<td>" . $val->last_activity_date . "</td>\n";
echo "</tr>\n";
}
Upvotes: 2