MySQL Forums
Forum List  »  PHP

How To Create dropdown menu in Mysql
Posted by: David Lam
Date: December 16, 2016 01:07AM

How To Create dropdown menu in Mysql
Hello everyone!

after reading so many warnings about the old mysql being deprecated I now switched to PDO.
I am currently trying to create a dropdown menu, which is connected to the database.
Here is the code I use:

<select name="subject">
<?php

$pdo = new PDO($dsn, $user, $pw);

try
{
/*** query the database ***/
$result = $pdo->query("SELECT subject_id, subject FROM subjects");

/*** loop over the results ***/
foreach($result as $row)
{
/*** create the options ***/
echo '<option value="'.$row['subject_id'].'"';

echo '>'. $row['subject'] . '</option>'."\n";
}
}
catch(PDOException $e)
{
echo 'No Results';
}
?>
</select>

The coded is included a form (don't want to paste the whole form code here, it is quite long).
The problem is that the form stops at the dropdown menu, which doesn't even show any options, just a 1 pixel sized option, which when I click on it, does not include any options.

I already solved the problem by deleting the connection code line though I have no idea why it then starts to work:

$pdo = new PDO($dsn, $user, $pw);

The problem recurs if I want to fill in the form a second time. So I have a link on the page that comes after the form is sent and you can fill it in and send it again, but then - tada - the form suddenly breaks at the 1 pixel sized dropdown menu, including no options anymore (with the same code as before, when it worked for the first time).

So I guess, it has something to do with my extremely trained PDO skills, but I just can't find the error. Furthermore, I would say that it is logic to connect first via the PDO connection code line in internet , right? But then it doesn't work from the start on and the form is stopped at the dropdown menu as described above (with the 1 pixel sized zero options).

I hope my problem is somehow understandable.

Another problem I have is that the dropdown menus with this code always already select an option at the start, is there a possibility to change the code so that it starts with an "empty" dropdown menu? So that it does not fill anything into the database if nothing is selected?
Thank's a lot!

Options: ReplyQuote


Subject
Written By
Posted
How To Create dropdown menu in Mysql
December 16, 2016 01:07AM


Sorry, you can't reply to this topic. It has been closed.

Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.