php populate option box from database table - php

I am writing code to register a new project via a html form. I want to be able to click a dropdown box which pulls the values from a table on the database.
At the moment a dropdown box displays but with no values.
PLEASE NOTE: I am a learning the basics so apologies if this is a simple question/answer scenario.
My code is below, any help is appreciated, I connect to the database via a php include script. The table is called 'customers' and the item I want to list is 'name';-
<?php
$result = mysql_query("SELECT customers FROM name");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
}
echo "</select>";
?>

"The table is called 'customers' and the item I want to list is 'name';" -
Do SELECT name FROM customers instead of SELECT customers FROM name
Using mysql_error() to mysql_query()
would have shown you the error that the table name does not exist.
Plus,
[name] are missing quotes inside them => ['name'] which are being treated as constants.
in
echo "<option value = '".$row[name]."'>".$row[name]."</option>";
as caught and kudos to devdesign
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
However, you are using a deprecated MySQL library. If you are still not getting results, then this could mean that you need to use (and should use) mysqli_ or PDO instead.
Here are a few links on the subject:
mysqli with prepared statements
PDO with prepared statements.

Your code should be. Also note the single quotes within $row['name']. You missed that.
<?php
$result = mysql_query("SELECT name FROM customers");
echo "<select name='client'>";
while($row = mysql_fetch_assoc($result))
{
echo "<option value = '".$row['name']."'>".$row['name']."</option>";
}
echo "</select>";
?>

Related

Echoing an Array as options inside a select box

I'm trying to create a select box full of options based on data from an array that is built from an sql query, I've tried researching where I'm going wrong but the closest I've managed to get is echoing alot of empty option boxes my code is as follows:
$result = mysqli_query($cons,"SELECT user_name FROM users");
while($row = mysqli_fetch_array($result)){
foreach($row as $key => $value){
echo '<option value="'.$value.'"</option>';}}
If anybody could point me in the right direction that would be great.
EDIT: I can't believe it was something as simple as that! Thank you very much.
On a separate note It's actually giving all of the data twice.
I'll mark as correct answer as soon as I can.
echo '<option value="'.$value.'">'.$value.'</option>';
or
echo "<option value=\"{$value}\">{$value}</option>";
You never closed the opening option tag. If you view your source you'll see it's wonky.
BTW, You don't need the value="" part if you're using the same value in the text of the option.
echo "<option>{$value}</option>";
Entire code as I would do it
$result = mysqli_query($cons,"SELECT user_id, user_name FROM users");
while($row = mysqli_fetch_assoc($result)){
echo "<option value=\"{$row['user_id']}\">{$row['user_name']}</option>";
}

Posting a value from Dropdown List from PHP div page

I'm having an issue in passing a value from a dropdown list that is in a separate PHP file that is being used by jquery.
I ended up getting the values from the dropdown list that isn't posting correctly by using jquery based on the value selected in the first dropdown list. The dropdown list in question is populating correctly, but with the way I have it setup I cannot post the value to the submit PHP page.
I'm pretty sure it has to do with the way I have it setup; however, I'm very new to jquery and was looking for some guidance.
The main PHP Page (the small areas in question)
<select name="department_list" id="department_list" onchange="$('#singleUser').load('get_users.php?nid='+this.value);">
...
<div id="singleUser" class="singleUser">
</div>
The PHP page (get_users) used to fill the values (only the area in question)
echo '<p style="text-align:center">';
echo "
<br />
Select a person to receive the form
<br />";
echo "<select id='userSelect' class='userSelect'>";
if ($id == '50') {
echo "<option value='Done'>Done</option>";
echo "</select>";
}else {
echo "<option value='none'>Select user</option>";
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stmt = $db->prepare("SELECT dm.empid AS empid, u.name AS name FROM mytable dm
JOIN mytable2 u ON dm.empid = u.id
WHERE dm.deptid = :id
ORDER BY u.name");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($r = $stmt->fetch()) {
$empid = $r['empid'];
$userName = $r['name'];
echo "<option value='".$empid."'>".$userName."</option>";
}
echo "</select>";
echo "</p>";
$db = null;
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
}//end else
In the submit page:
if(isset($_POST['userSelect'])){
$givenID = $_POST['userSelect'];
//the rest of my code
I do have the div code above within the form tags and have method="post". All of my other inputs post correctly, so I'm thinking it has to do with the way I have only the div tags within the main page. Again, I'm pretty new to all of this so any ideas or changes that I should make so it posts correctly would be greatly appreciated.
You forgot the name of the select when you write it with php:
change this:
echo "<select id='userSelect' class='userSelect'>";
to
echo "<select id='userSelect' name='userSelect' class='userSelect'>";
i think the error is in the PHP file generating the user select it is missing the name attribute name="userSelect"
echo "<select id='userSelect' class='userSelect'>";
it should be
echo '<select id="userSelect" name="userSelect" class="userSelect">';
every form element with the name attribute gets posted with its value. if you do not enter the name attribute, the value can not be retrieved from the $_POST array. Also have in mind that disabled form inputs also do not get posted.
Edited the PHP quotes. Use Single qutes everyt time you do not need to insert PHP variable into the string. It is ~9 times faster than double quotes ;)

php drop down print selected item

I am trying to print the selected dropdwon item. I have already written the code for dropdown to fetch a column from database.
Now i should print the only the id of selcted dropdown item. i don't know how to make it. please help me, this is my code
<?
$query_name="SELECT id_cat,name FROM `fs01_metier_cat` ORDER BY `fs01_metier_cat`.`name` ASC";
$result = mysql_query ($query_name);
echo "<select name=category value=''></option>";
while($nt=mysql_fetch_array($result))
{
echo "<option value=$nt[name]>$nt[name]</option>";
}
echo "</select>";
$query_id="SELECT id_cat FROM `fs01_metier_cat`";
$result1 = mysql_query ($query_id);
while($row = mysql_fetch_assoc($result1))
{
echo $row['id_cat'];
}
?>
try this:
while($nt=mysql_fetch_array($result)){
echo "<option value='{$nt['id_cat']}'>{$nt['name']}</option>";
}
with {} php can insert also array values into a string and you should set ' ' around the attribute "value"'s value (alot of values here.. ^^), that the html is w3c conform (i dont know if a browser would take it as correct without them..)
without the { } it would look like that:
while($nt=mysql_fetch_array($result)) {
echo "<option value='".$nt['id_cat']."'>".$nt['name']."</option>";
}
depending on your editor code highlighting might work better in the second case ;)
and about the selected item:
i would suggest you to use jQuery to get the content of the selected item
var selectedId = $('#yourselectid option:selected').attr('value');
and then you can e.g. write it to the document or to a div:
document.write(selectedId);
or
$('#yourDivIdWhereYouWantToPutTheSelectedId').html(selectedId);
important: please note that i changed the value's index to id_cat because then you can handle the options with their id
Since the selected option changes everytime you change the dropdown selection, you can not handle this via php. There are ways to do that without a huge library like jQuery (since they are also just simple Javascript) but they simplify such things alot ;)

No result from options selected from a database column (php-mysql)

In the PHP code below i want to select all the column values of a table and make them options of a select form. The result is that i dont get any options at all. Could someone help? Thanks
<?php
// ....
$userid=$_SESSION['userid'];
echo "<select>";
$sql = "SELECT * FROM users where userid='".$userid."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo "<option>" .$row['company']. "</option>";
}
echo "</select>";
mysqli_close();
?>
It may just be a typo but you have mixed mysql and mysqli functions, you have stated mysql_query and mysql_fetch_array, whereas you have closed it with mysqli_close, could be an issue depending on what you wrote above this code or indeed if this is not just a typo.
Other things to try would be try the query in your mysql client / phpmyadmin and see if it comes up with any results or errors.

retrieve mysql data as array and display in multiple combo boxes

i am trying to use the mysql data items into the select combo box. it basically works well but the problem is when there are multiple combo boxes it is a lot of load to the server since adding each combo box takes a lot of time. i am trying to figure out a better way. may be pull date once into an array just for the session and place it in the combo boxes.
The logic is basically it is a quotation form where about 3500 items will be shown as drop down and user will select and then enter price and other details. the rows are dynamically added or deleted by the user.
i am currently using the following code:-
<?php
$con = mysql_connect('blah blah blah');
if (!$con) {
die ('Could not connect: ' . mysql_error());}
$db = mysql_select_db('blah',$con);
$extract1 = mysql_query("query") OR die (mysql_error());
$numrows1 = mysql_num_rows($extract1);
echo "<select name='itemname' title='select Item Name'>";
echo "
<option>Select Item Description</option>
";
while ($row1=mysql_fetch_assoc($extract1))
{
$ic=$row1['ItemName'];
echo "
<option>$ic</option>
";
}
echo "</select>";
mysql_close($con);
?>
Don't echo your option do this in your while statement:
$ic[]=$row1['ItemName'];
then outside of the while loop anywhere on the page:
foreach($ic as $i){
echo "<option>".$i."</option>";
}
First off, Don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
<?php
$con = mysql_connect('blah blah blah') or die(mysql_error());
$db = mysql_select_db('blah',$con) or die(mysql_error());
$result = mysql_query("query MAYBE NARROW DOWN TO MORE RELEVANT RESULT SET") or die (mysql_error());
$option = '<select size="1" name="optionBox">';
if(mysql_num_rows($result)>=1){
while ($row=mysql_fetch_assoc($result)){
$option .="<option selected value=\"".$row['ItemName']."\">".$row['ItemName']."</option>\n";
}
}else{
$option .='<option selected value="0">No items to list</option>';
}
$option .='</select>';
echo $option;
mysql_close($con);
?>
Yes, if your data changes infrequently enough, it may be a good idea to put the data into an array on the session, and render it from there. Depending on the frequency of change of your data, you might be able to get away with rendering it to a non-session data element (for example, a file on your filesystem) and populating your comboboxes from there (or just rendering all your choices into the combobox elements in that file, and using that data directly); that depends on the frequency by which your data is updated, of course.

Categories