PHP and OCI, Populate a drop down menu - php

I want to populate a html drop down menu with a list query from database. I have the following...
<?php
$conn = oci_connect(//connection stuff goes here//);
$stid = oci_parse($conn, "SELECT DESCRIPTION FROM COUNTRY WHERE COUNTRY_ID IS NOT NULL");
$result = oci_execute($stid, OCI_DEFAULT);
echo '<select>';
while ($row = oci_fetch_array($result)) {
echo '<option value=' . $row['DESCRIPTION'] . '</option>';
}
echo '</select>';
?>
Something to with the qoute marks on the echo line? Any help here would be great :)

This question has nothing to do with Oracle. Just replace this:
echo '<option value=' . $row['DESCRIPTION'] . '</option>';
... with this:
echo '<option>' . htmlspecialchars($row['DESCRIPTION']) . '</option>';
You were basically generating this:
<option value=Blah Blah Blah</option>
Edit: And you forgot about COUNTRY_ID! Add it to the SELECT statement and use it:
echo '<option value="' . htmlspecialchars($row['COUNTRY_ID']) . '">' . htmlspecialchars($row['DESCRIPTION']) . '</option>';

Yes, your assumption was right, you have to enclose your description in double quotes and also insert it inside the tags, like this:
echo '<option value="' . $row['DESCRIPTION'] . '">'.$row['DESCRIPTION'].'</option>';

Related

How to populate select options from DB

What am I doing wrong here? When it populates the options it shows $name[0] and not the info from the DB. Though the correct number of options seem to be available.
<?php
//connect to database
$conn = mysqli_connect("example.com", "timemin", "Pass123", "timesheet");
//query database for items to populate
$sql = "SELECT DIS_NAME, NAME FROM INVITEM";
$query = mysqli_query($conn, $sql);
echo '<select>';
echo '<option value="">Choose your favorite fruit</option>';
while($name = mysqli_fetch_assoc($query)){
echo '<option value="' . '$name[1]' . '">' . '$name[0]' . '</option>';
}
echo '</select>';
echo $query;
?>
Should be as follows, you quoted variables, that was the problem.
echo '<option value="' . $name['DIS_NAME'] . '">' . $name['NAME'] . '</option>';
Also as RiggsFolly mentioned, you used fetch_assoc so the array keys will be named accordingly DIS_NAME and NAME.
Credit to RiggsFolly for spotting this.
In php, there are two types of quotes: single quotes and double quotes. Single quotes will not parse variables, double quotes will.
If you do want to use quotes, you could do something like this:
echo "<option value="."$name[1]".">$name[0]</option>";
So here, the double quotes will tell php to parse the variable names
However, I would recommend doing this:
echo '<option value="' . $name[1] . '">' . $name[0] . '</option>';
See this SO post for more.

options are not getting printed/echoed?

This page generates the option pulled from database . another page brings here the year of joining of students via year_joining . rest of the mysql queries works absolutely fine ( tested )
<?php
include_once("../Include/connectdb.php");
if($_GET['year_join'])
{
$id=$_GET['year_join'];
$result1 = mysql_query("select distinct sub_id from subject_profile where batch='$id'
")or die(mysql_error());
while($subid = mysql_fetch_assoc($result1)){
$result2 = mysql_query("SELECT name FROM `subjects` WHERE `sub_id` LIKE
'$subid[sub_id]'");
$subject=mysql_fetch_assoc($result2);
if($subject[name]!=""){
//print "<OPTION value=".$tmp.'">'.$tmp.'</OPTION>';
//print "<OPTION value='$tmp'>'$tmp'</OPTION>";
echo "<option value=".$subject['name'] . '">' . $subject['name'] . '</option>';
//echo '<option value="'.$id.'">'.$data.'</option>';
//}
}
}
}
?>
FYI :
//print "<OPTION value=".$tmp.'">'.$tmp.'</OPTION>';
//print "<OPTION value='$tmp'>'$tmp'</OPTION>";
echo "<option value=".$subject['name'] . '">' . $subject['name'] . '</option>';
//echo '<option value="'.$id.'">'.$data.'</option>';
none of these are working ... :(
with simple echo $tmp it works
but when ever i put as
echo "<option value=";
the result is blank page ...
and when i am echo - ing just the variable its works perfectly fine
echo $tmp;
gives the list of all the subjects ..
For the problem regarding "not displaying output", I believe you have missed a <select> tag enclosing the <option> tags.
As a side note, in the query, change it like this:
"SELECT name FROM `subjects` WHERE `sub_id` LIKE '{$subid[sub_id]}'"
or,
"SELECT name FROM `subjects` WHERE `sub_id` LIKE '" . $subid[sub_id] . "'"
Still it is not safe. You should escape the values and better use a prepared statement using mysqli or PDO
The main problem is as per Akhilesh B Chandran's answer, with a missing <select> tag.
Other than that, there will be a problem when $subject['name'] has a space in it.
The problem is this line:
echo "<option value=".$subject['name'] . '">' . $subject['name'] . '</option>';
It should be like this:
echo '<option value="'.$subject['name'] . '">' . $subject['name'] . '</option>';
In what you currently have, the browser interprets the result as this:
<option value=insert name here">insert name here</option>
As it is visible, there is a missing quote after value=.
Your quotes don't match up, which is why PHP is failing.
Try changing:
echo "<option value=".$subject['name'] . '">' . $subject['name'] . '</option>';
to:
echo "<option value=".$subject['name'] . ">" . $subject['name'] . "</option>";
Basically, you start off using a ", and switch partway through to using '

How to Populate Dropdown List's text and value from MySQL?

I am using mysqli to query a database table to obtain the value for a dropdownlist. However, I also want to retrieve the corresponding description and load that into the option text. My query is as follows:
<?php
$query=('SELECT restaurantid,location from restaurant');
$result = mysqli_query($mysqli,$query);
echo '<select name="ddlStore">';
while($row=$mysqli->fetch_array($result))
{
echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">';
'</option>';
}
echo '</select>';
?>
How do I revise the above so that the location field is populating in the dropdownlist's option text?
Updated code:
<?php
$query=('SELECT restaurantid,location from restaurant');
$result = mysqli_query($mysqli,$query);
echo '<select name="ddlStore">';
while($row=$mysqli->fetch_array($result))
{
echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">' .
htmlspecialchars($row['location']) .
'</option>';
}
echo '</select>';
?>
The above still does not display the locations as dropdownlist option text values.
Update #2:
When viewing the page, the dropdownlist doesn't show the values from the database table. Using IE Developer Tools, I see a script error in the while statement:
Call to undefined method mysqli::fetch_array()
Is there a more optimal way to structure the mysqli_fetch_array statement?
Change to...
echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">' . htmlspecialchars($row['location']) . '</option>';
echo '<option value="' . htmlspecialchars($row['restaurantid']) . '">' . htmlspecialchars($row['location']) . '</option>';
But what have you tried so far?
Try this way (more info here)
$result = $mysqli->query($query)
while($row = $result->fetch_assoc()) {
}

mysql database making drop down menu using data already entered in html/php

I created a database with 3 tables being spusername, splocation, sprecord. spusername has id, splocation_id, lastname, firstname. I want to be able to have a drop down menu that has pulled id, lastname, firstname from the database, and within the pulldown it only shows a list of all the names being lastname,firstname. then once I select a person I have another drop down that has types of training in it. then when I hit submit it will generate a record in another table with the persons id and training record. so when I do a search it will pull up the user and the training records for that person.... I have already created a submit page in a .php that sends lastname, firstname, splocation_id for new users and I think I can create a search that does what I want it to, but I have never made a data entry doing a pulldown that has values generated from the database.
EDIT Code: With help from Vegard's coding I got this, and now it works great after a few trial and errors. Thank You!
Code:
<?php
if (isset($_REQUEST['Submit'])) {
$sql = "INSERT INTO $db_table(spusername_id,sptraining_id) values ('".mysql_real_escape_string(stripslashes($_REQUEST['spusername_id']))."','".mysql_real_escape_string(stripslashes($_REQUEST['sptraining_id']))."')";
if($result = mysql_query($sql ,$db)) {
echo '<h1>Thank you</h1>Your information has been entered into the database<br><br>';
} else {
echo "ERROR: ".mysql_error();
}
} else {
?>
<h1>Add Training Information To Database</h1><hr>
<br><br>
<form method="post" action="">
<select name="spusername_id">
<option value="default">Select Employee</option>
<?php
include("connectspusers.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY lastname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['lastname'] . ' ' . $row['firstname'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>';
}
?>
</select>
<select name="sptraining_id">
<option value="default">Select Training</option>
<?php
include("connectsptraining.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, trainingtype, level FROM sptraining ORDER BY level ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['id'] . ' ' . $row['trainingtype'] . ' ' . $row['level'] . '">' . $row['trainingtype'] . ' - ' . $row['level'] . '</option>';
}
?>
</select>
<br><br>
<input type="submit" name="Submit" value="Submit">
</form>
<?php
}
?>
Something like this?
<select name="pulldown1">
<option value="default">Choose an option</option>
<?php
include("connect.php"); /*file where you have stored your DB conn. settings*/
$result = mysql_query('SELECT id, lastname, firstname FROM spusername ORDER BY firstname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . htmlentities($row['id'], ENT_QUOTES) . ' ' . htmlentities($row['lastname'], ENT_QUOTES) . ' ' . htmlentities($row['firstname'], ENT_QUOTES) . '">' . htmlentities($row['lastname'], ENT_QUOTES) . ', ' . htmlentities($row['firstname'], ENT_QUOTES) . '</option>';
}
?>
</select>
<select name="pulldown2">
<option value="default">Choose and option</option>
<?php
$result = mysql_query('SELECT traingtype FROM trainingtable ORDER BY trainingname ASC') or die (mysql_error());
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['trainingtype'] . '">' . $row['trainingtype'] . '" "' . $row['lastname'] . '</option>';
}
?>
</select>
This will result in two dropdown menus where the first dropdown lists the users last- and firstname separated by a comma+space and the second will list the different types of training. The ID filed is only sendt via the variable, but not displayed to the user.
When pulling the values from the variable in pulldown1, just use explode:
$userdetails = $_POST['pulldown1'];
$values = explode(" " $userdetails);
$ID = $values[0];
$lastname = $values[1];
$firstname = $values[2];
Haven't tested the code so it might need tweaking, and ofcourse you need to change the variable names corresponding to your actual db rownames.
Edit: In your code, you have to use $row and not $row2.
Secondly, instead of this:
<option value='{$id}'>{$lastname},{$firstname}</option>
use this:
<option value="' . $row['id'] . '">' . $row['lastname'] . ', ' . $row['firstname'] . '</option>
<select name="id" size="1">
<?php
$result=mysql_query("select * from spusername;");
while($user=mysql_fetch_array($result)) {
echo "<option value=\"".$user['id']."\">".$user['lastname'].", ".$user['firstname']."</option>";
?>
</select>
Go on with always using "id" as a reference to the user and try using post instead of get to send the request(keeps the URL in your user's browser clean).
You build a select in a loop with the data from your database.
example with mysql (did not test):
$query = "select id, lastname, firstname from spusername";
$result = mysql_query($query);
echo "<select>";
while($row = mysql_fetch_array($result)){
echo "<option value='".$row['id']."'>".$row['lastname']. " ". $row['firstname']."</option>";
}
echo "</select>";
EDIT: (response to your edit)
In your code you use $row2 instead of $row
Just an addendum to Vegard's solution:
Single quotes can be a bit tricky with surnames. It really depends on how you're storing the data in your database though.
If you have a surname O'Leary or O'Reilly you might get truncated results as you're building your select loop on the names. Give it a try.
You can fix this issue by using
htmlentities($row['lastname'], ENT_QUOTES) in your select loop

Pre-filling select tags from array

I've got this array:
$profession_type = array(
'Professional Engineers',
'Accountants',
'Insurance Professionals',
'Attorneys',
'Certified Hazardous Materials Managers',
'Safety Professional',
'Industrial Hygienists',
'IT Professionals',
'Human Resource'
);
I am display the contents of the array as the options for the select tag:
<select name="profession_type[]">
<option value=""></option>
EOL;
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
print <<<EOL
</select>
I've never pre-filled a drop down box with dynamic values. The values in $profession_type will change frequently (and will eventually be driven from a table in the db), so I can't do hard code it.
EDIT: Sorry my question was unclear.
The user will select a value from a previous screen (say it's called id) and hit submit.
Before the HTML is rendered to the screen, PHP makes a stored procedure call based on the id they selected.
The values that the stored procedures returns will prefill the "profession_type[]" form field.
I would like the <option value='accountants' selected>Accountants</option> if the stored procedure returns "Accountants" for the value of "profession_type" based on the id.
Is that more clear? Sorry.
Any suggestions?
How about this:
print '<select name="profession_type">';
print '<option value=""></option>';
foreach ($profession_type as $p)
{
if ($p == $chosen_profession)
print "<option value='" . $p . "' selected='selected'>" . $p . "</option>";
else
print "<option value='" . $p . "'>" . $p . "</option>";
}
print '</select>';
This goes in your .php file:
<!-- some HTML here -->
<?php
$profession_type = [result_from_database_query] ?>
<!-- more HTML here -->
<select name="profession_type">
<?php
foreach ($profession_type as $p){
print "<option value='" . $p . "'>" . $p . "</option>";
}
?>
</select>

Categories