Ovic
Ovic

Reputation: 45

Trying to load data dynamically from the database in a from using PDO

Im trying to load data from the database dynamically. Like when user click on select button in a form, the data will be loaded dynamically from the database. But the problem is I have to use PDO. Im not getting the output, don't know what's wrong. Here is my code-

<tr><td><font size="+1">Region   :</font></td>
<td><Select name="region" class="regionfields" id="wineRegion">
<option id="0">-- Select Region --</option>
<?php

$hostname = 'localhost';

$username = 'ovic';

$password = 'root';

try {
$dbh = new PDO("mysql:host=$hostname;dbname=winestore", $username, $password);

echo 'Connected to database<br />';


$sql = "SELECT region_name FROM region";


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


$obj = $stmt->fetch(PDO::FETCH_OBJ);


foreach($obj->region_name AS $W)
{?>

<option id="<?php echo $W; ?>"><?php echo $W; ?></option>
<?php

}

/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
</Select></td></tr>

Upvotes: 0

Views: 401

Answers (1)

jonstjohn
jonstjohn

Reputation: 60276

You may need to use $stmt->fetchAll() which returns an array of objects. The fetch() method returns only a single object.

$regions = $stmt->fetchAll(PDO::FETCH_OBJ);
foreach ($regions as $region) {
?>
    <option id="<?php echo $region->region_name; ?>">
        <?php echo $region->region_name; ?></option>
<?php
}

If that fails, trying doing a print_r on the result of fetchAll() to see if you are getting anything back.

Upvotes: 1

Related Questions