webdev.gk webdev.gk - 1 year ago 143
MySQL Question

Convert to PDO type mysql_fetch_array

I would like to ask for assistance on how to convert the code below to PDO type especially the mysql_fetch_array. I can make it work properly using this code but I want to convert to PDO.


$query = "SELECT * from name";
$result = mysql_query($query);

$cols = 6;
echo "<table>";
do {
echo "<tr>";
for ($i = 1; $i <= $cols; $i++) {

$row = mysql_fetch_array($result);
if ($row) {
$name = $row['fname'];
<tr valign="top">
<?php echo '<input type="checkbox" name="name[]" id="name[]" value="' . $name . '"/>' . $name . "\n"; ?>
<td width="30">&nbsp;</td>
} else {
echo "<td>&nbsp;</td>";
} while ($row);
echo "</table>";

Answer Source

First off, you can read more at http://php.net/pdo.

$dsn = 'mysql:dbname=testdb;host=';
$user = 'dbuser';
$password = 'dbpass';

try {
    $dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();

$query = "SELECT * from name";

$stmt = $dbh->prepare($query);


// Start your html col/row setup

// Loop through your cols

$row = $stmt->fetch(PDO::FETCH_ASSOC);

For your example it's not necessary to 'prepare' however it is a good practice when you start passing values to your query.

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