I'm working on an exercise where I"m supposed to display all data contained in a table. Here's the solution I can up with:
<?php
$result = mysql_query("SELECT * FROM contacts ORDER BY id DESC");
while($user= mysql_fetch_array($result)) {
echo $user['first'] . " " . $user['last'] . "<br />" . $user[phone] . "br />";
}
?>
Here's the solution the tutorial gave:
<?php
$result=mysql_query("SELECT * FROM contacts ORDER BY id DESC");
$num=mysql_num_rows($result);
$i=0;
while ($i < $num) {
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$phone=mysql_result($result,$i,"phone");
echo "<b>$first $last</b><br>Phone: $phone<br><hr><br>";
$i++;
}
?>
The database fields are:
id
first
last
phone
Can someone explain WHY one is better than the other. They both work as far as I can tell.
*EDIT: I've rewritten the query based on the advice given by @Paul below: *
<?php
$pdo_connect = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
$statement = $pdo_connect ->query("SELECT * FROM users ORDER BY id DESC");
while($user = $statement->fetch(PDO::FETCH_ASSOC)) {
echo "{$user['first']} {$user['last']} <br /> {$user['phone']} <br /><hr>";
}
?>