-1

I am trying to get a column from mysql database into a drop down list but the following error is displaying every time.

Code:

<?php  
$db_host = "localhost"; 
$db_username = "root";  
$db_password = "root";  
$db_name = "my_database";

try {
    $dbh = new PDO("mysql:host=$db_host;dbname=$db_name", $db_username, $db_password);
}
catch(PDOException $e) {
    echo $e->getMessage();
}
?>
<form action="members.php" method="POST">
    <select name='access_country' onchange='this.form.submit()'>
        <?
        $dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $stmt = $dbh->prepare("SELECT Country FROM AccessNumbers"); //Line No: 362
        $stmt->execute();
        while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            echo "<option value=".$row['Country'].">".$row['Country']."</option>";
        }
        ?>
    </select>
</form>


Following error is displaying:

PHP Fatal error:  Call to a member function prepare() on a non-object in line 362
sohal07
  • 440
  • 8
  • 21
  • where do you create the $dbh object? – Steve Feb 05 '14 at 14:13
  • thats on top of the page....i haven't pasted all the code on the page. – sohal07 Feb 05 '14 at 14:15
  • Can you show the connection statement? – hjpotter92 Feb 05 '14 at 14:16
  • Please show the FULL code – Steve Feb 05 '14 at 14:16
  • Apart from `$dbh` not being an object, why do you use a prepared statement that has no parameters? That should be a query, not prepared statement. – N.B. Feb 05 '14 at 14:18
  • See [how to squeeze an error message out of PDO](http://stackoverflow.com/questions/3726505/how-to-squeeze-error-message-out-of-pdo). By default, it errors silently. Set it up to throw exceptions, and you'll more easily see what went wrong. – Michael Berkowski Feb 05 '14 at 14:22
  • @MichaelBerkowski: It does have error handler, i have just updated the code. – sohal07 Feb 05 '14 at 14:25
  • You are certain you didn't see another error from the initial `try/catch`? And you are certain that you didn't overwrite `$dbh` somewhere else in code not posted? If the connection failed initially, your `catch` block would have executed and you would see an error. – Michael Berkowski Feb 05 '14 at 14:26

1 Answers1

0

Have no idea what exactly the problem was.
I simply restarted my MAMP server and accessed the page. And it was working.

sohal07
  • 440
  • 8
  • 21