Reputation: 5377
I am trying to convert the Mysqli code to use PDO
Mysqli code looks like the following (which works great)
$rs = "SELECT * FROM team";
$result = mysqli_query($con,$rs);
$data = mysqli_num_rows($result);
$responses = array();
if($data != 0) {
while($results = mysqli_fetch_assoc($result))
{
echo "<tr><td>".$results['code'] ."</td>";
echo "<td>".$results['username'] ."</td>";
}
My PDO code I tried
$stmt = $con->prepare("select * from team");
$stmt->execute();
if($stmt->rowCount() > 0)
$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);
How should I write a while loop here
on w3schools website, the information given to retrieve the records using PDO is as below, which did not say what is V and doesn't say how do I retrieve the fields code
and username
from the table.
foreach(new TableRows(new RecursiveArrayIterator($stmt->fetchAll())) as $k=>$v) {
echo $v;
}
Upvotes: 0
Views: 1311
Reputation: 237865
That's a horrifically awful way to select data from a database. It's far more complex than is necessary. I suppose it might be useful in a certain context, but not here.
The simple way is with PDOStatement::fetch
. This works in much the same way as mysqli_fetch_assoc
. (You don't strictly speaking need to check the row count, though you might have other code if there are no results.)
while ($row = $stmt->fetch()) {
echo "<tr><td>".$row['code'] ."</td>";
echo "<td>".$row['username'] ."</td>";
}
My preferred way, however, is with PDOStatement::bindColumn
, which gets rid of arrays and uses nice plain variables instead:
$stmt->setFetchMode(PDO::FETCH_BOUND);
$stmt->bindColumn('code', $code);
$stmt->bindColumn('username', $username);
while ($row = $stmt->fetch()) {
echo "<tr><td>$code</td>";
echo "<td>$username</td>";
}
Upvotes: 3
Reputation: 823
$rs = "SELECT * FROM team";
$stmt = $pdo->query($rs );
while ($row = $stmt->fetch())
{
echo "<tr><td>".$row ['code'] ."</td>";
echo "<td>".$row ['username'] ."</td></tr>";
}
or
$stmt = $pdo->query($rs );
foreach ($stmt as $row)
{
echo "<tr><td>".$row ['code'] ."</td>";
echo "<td>".$row ['username'] ."</td></tr>";
}
or
$data = $pdo->query($rs )->fetchAll();
foreach ($data as $row)
{
echo "<tr><td>".$row ['code'] ."</td>";
echo "<td>".$row ['username'] ."</td></tr>";
}
Upvotes: 2
Reputation: 157863
It's PDO, so everything is MUCH simpler:
foreach ($con->query("SELECT * FROM team") as $results) {
echo "<tr><td>".$results['code'] ."</td>";
echo "<td>".$results['username'] ."</td>";
}
Upvotes: 3
Reputation: 166
$stmt = $con->prepare("select * from team");
$stmt->execute();
if($stmt->rowCount() > 0)
{
while($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "<tr><td>".$row['code'] ."</td>";
echo "<td>".$row['username'] ."</td>";
}
}
Upvotes: 2