0

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>

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.