I have a web site that contains an HTML form, in this form I have a dropdownlist with list of agents that works in the company, I want to fetch data from MySQL database to this dropdownlist so when you add a new agent his name will appear as an option in the drop down list.
<select name="agent" id="agent">
</select>
To do this you want to loop through each row of your query results and use this info for each of your drop down's options. You should be able to adjust the code below fairly easily to meet your needs.
// Assume $db is a PDO object
$query = $db->query("YOUR QUERY HERE"); // Run your query
echo '<select name="DROP DOWN NAME">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo '<option value="'.htmlspecialchars($row['something']).'">'.htmlspecialchars($row['something']).'</option>';
}
echo '</select>';// Close your drop down box
# here database details
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);
echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";
# here username is the column of my table(userregistration)
# it works perfectly
You need to fetch all rows from the database and then iterate over them, displaying a new <option> for each one of them. Pay attention to avoid XSS by using htmlspecialchars().
$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_EMULATE_PREPARES => false
]);
// Select all values from the table Agents
$stmt = $pdo->prepare("SELECT Id, Name FROM Agents");
$stmt->execute();
echo '<select name="agent" id="agent">';
// For each row from the DB display a new <option>
foreach ($stmt as $row) {
// value attribute is optional if the value and the text is the same
echo '<option value="'.htmlspecialchars($row['Id']).'">';
echo htmlspecialchars($row['Name']); // The text to be displayed to the user
echo '</option>';
}
echo '</select>';
If you want to preselect one of the values, then you need to apply selected attribute to one of the <options>:
$selected = 'Somebody';
echo '<select name="agent" id="agent">';
foreach ($stmt as $row) {
if ($selected === $row['Name']) {
echo '<option value="'.htmlspecialchars($row['Id']).'" selected >';
} else {
echo '<option value="'.htmlspecialchars($row['Id']).'">';
}
echo htmlspecialchars($row['Name']);
echo '</option>';
}
echo '</select>';
What you are asking is pretty straight forward
execute query against your db to get resultset or use API to get the resultset
loop through the resultset or simply the result using php
In each iteration simply format the output as an element
the following refernce should help
HTML option tag
Getting Datafrom MySQL database
hope this helps :)
Related
I've set up a php form that registers a project to our database, it has a drop down that populates from our customer/supplier databases.
I've also set up a function to edit these projects, the problem I have is that when I go to my edit page it just displays the customer/supplier name and not in the drop down but a value box - is there a way to have the edit page display the dropdown but also be selected on the original supplier/customer?
Register project page
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo '<select name='client'>';
while($row = mysql_fetch_assoc($result))
{ `
echo '<option value = ''.$row[name].''>'.$row[name].'</option>';
}`
echo '</select>';
?>
Edit page
<input type='text' name='client' value='<?php echo $client; ?>'/>
I tried a few tutorials and code tweaks but kept getting errors. I am aware of my sql injection problem, at the moment this site is internal.
Any help would be appreciated.
thanks
instead of $row[name] you should use $row['name']
$client= "<select name='client'>"; // you had error here also.
while($row = mysql_fetch_assoc($result))
{
$client.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
$client.= '</select>';
now echo $client to get dropdown.no need of constructing separate select tag now.
for selected use like this:
$client1= "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
if($row['name'] == $clientValue){
$client.= "<option selected='selected' value = '".$row['name']."'>'".$row['name'].'</option>';
}else{
$client1.= "<option value = '".$row['name']."'>'".$row['name'].'</option>';
}
}
$client1.= '</select>';
on echo of $client1 you will get selected based on the value $clientValue which you have to pass.
On your edit page:
<?php
$result = mysql_query('SELECT name FROM customers ORDER BY name ASC');
echo "<select name=\"customer\">";
while($row = mysql_fetch_assoc($result))
{
if ($row['name'] == $client)
{
echo "<option selected value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
else
{
echo "<option value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
}
}
echo "</select>";
?>
I also suggest that you change the old extension for mysql. I can't see no SQL Injection problem for now, but you should take care of it even if it is internal, because, from different reasons you will forget to sanitize it later. If you are writing it, then write it correctly.
Now for the problem, you are not using the quotes correctly, hence the errors. Do not use the same type of quotes, but change them, like so:
echo '<select name="client">';
Or if you use double quotes for concatenation, use single inside.
In case you have to use the same, escape them with \
For starters, you have a syntax error here:
echo '<select name='client'>';
(There are probably more quoting errors throughout the code, but I digress...)
As for using a drop-down, what you're looking for is the selected attribute. When you're building the page elements to display the form on the "edit" page, presumably you have the values that you're looking to display. When your loop finds an element which matches the value, select it:
while($row = mysql_fetch_assoc($result))
{
if ($knownValue == $row[name]) {
echo '<option selected value = ''.$row["name"].''>'.$row["name"].'</option>';
} else {
echo '<option value = ''.$row["name"].''>'.$row["name"].'</option>';
}
}
I have a problem when I retrieve data from database the result is
How to retrieve the data normally?
This is my codes..
$wewqry = $mysqli->prepare("SELECT itemname from table_item ");
$wewqry->execute();
$wewqry->bind_result($itemname);
$wewqry->store_result();
while ($wewqry->fetch()){
$table = array("itemname" => $itemname);
foreach ($table as $t => $w){
echo '<select name="itemname">';
echo "<option>$w</option>";
echo '</select>';
}
}
You should not create a new <select> each time through the loop, do it once outside the loop:
echo '<select name="itemname">';
while ($wewqry->fetch()) {
echo "<option>$itemname</option>";
}
echo '</select>';
You also don't need to make an array for each row you fetch. Just insert the result variable directly into the echo statement.
I use the following code to create a number of drop-down lists with the same values. The values are brought in from an MSSQL table via a query written elsewhere.
<?php
$select = '';
while($row = $data->fetch(PDO::FETCH_BOTH))
{
$select .= "<option value='".$row['Code']."'>".$row['Code']."</option> ";
}
echo "<select name=\"proj1[]\">";
echo $select;
echo "</select>";
?>
The user makes his selections, then submits the form and the record is written to the PROJECTS table in the PROJ DB (fields: Proj1, Proj2, Proj3, Proj4). The original drop-down values are held in a separate table (CODES). When the record is called up in a browser, a prepared SELECT statement runs against PROJECTS to load it. I would like to show the user the drop-down selections he made when the completed form is loaded, i.e., the values of Proj1-Proj4 for a given record in PROJECTS. How can I do this? I'm not sure where to put my 'option selected'.
Hope this help
$select = '';
while($row = $data->fetch(PDO::FETCH_BOTH))
{
$select .= "<option value='".$row['Code']."' '".$row['Code'] == $_POST['proj1'] ? ' selected="selected"' : ''."' >".$row['Code']."</option> ";
}
echo "<select name=\"proj1[]\">";
echo $select;
echo "</select>";
I am trying to populate a selection box (dropdown) from a mysql table in php, but I get blank results, Can someone look in my code and tell me what is wrong?
I need to populate the select with the dates available from my sql query, so they show up as seletion options....
<?php
echo JText::_('Please select the date:');
$database= &JFactory::getDBO();
$database->setQuery('SELECT training_id,training,trainingDate FROM training');
$result = $database->loadObjectList();
echo '<select name="whatever">';
foreach ($result as $row) {
echo '<option value="'.$row->training_id.'" />';
}
echo '</select>';
?>
You assign an option value, but you don't provide human-readable option text:
echo '<select name="whatever">';
foreach ($result as $row) {
<!-- here we go -->
echo '<option value="'.$row->training_id.'">'.$row->training.'</option>'; // always close options!!!
}
echo '</select>';
echo '<option value="'.$row->training_id.'">'.$row->trainingDate.'</option>';
If that doesn't work then your $row->training_id isn't set and so you'll need to debug that (e.g. doing a print_r($row) just before that line to see what is inside the $row object)
Try this:
while($row = mysql_fetch_object($result)) {
instead of this:
foreach($result as $row) {
I have read tutorials about how to populate an entire Drop down list with MySQL, but the problem I am running into is that I only want to grab the one from the database and have that be the selected one. So I would have like a drop down with three items (Item1, Item2, Item3) in the database its stored in a column called itemschoice which has a value of 'Item2'. How do I go about getting item2 to be selected when I load the drop down box?
In your <option> element add the selected attribute for the value that is in itemschoice.
Crude example using a made up function to get the choice:
$choice = get_items_choice();
$results = mysqli_query($sql);
echo '<select name="whatever">';
while($row = mysqli_fetch_array($results)) {
if ($row['choice'] === $choice) {
echo '<option value="' . $choice . '" selected="selected" />';
} else {
echo '<option value="' . $choice . '" />';
}
}
echo '</select>';
This is just an example, don't copy & paste this without adding some kind of error verification!