populate dropdown list with database value - php

I want to populate a drop down list with data from a specific field in the database. Here is my sample code
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("disertation ", $con);
$results = mysql_query("SELECT name FROM user_parent;");
?>
<select name="name">
<option value="name">Select one</option>
<?php
while($row=mysql_fetch_array($results))
{ echo '<option value=" ' . $row['name'] . ' ">' . $row['name'] . '</option>'; }
?>
</select>
It's currently displaying nothing from db, any help?

Try this, some white space in your code mysql_select_db("disertation", $con);
mysql_select_db("disertation", $con);
$results = mysql_query("SELECT name FROM user_parent") or die (mysql_error());

Make your mysql_fetch_array call read:
mysql_fetch_array($results, MYSQL_ASSOC)
Without MYSQL_ASSOC you can't refer to column names in $row.
Also, consider using MYSQLI or PDO. MYSQL is considerably outdated.

I would recommend you to use mysqli instead of mysql
<?php
$con=mysqli_connect("localhost","root","","disertation ");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$resource= mysqli_query($con,"SELECT * FROM user_parent");
echo "<select class="name"><option value="name">Select one</option>";
while($result = mysqli_fetch_array($resource)){
echo '<option value="'.$result["name"].'">'.$result["name"].'</option>';
}
echo "</select>";
mysqli_close($con);
?>

To answer your question, directly, you should be first checking if there are any errors (mysql_error()) and then checking there are some results (mysql_num_rows) - these make for easier debugging of your code, since it will tell you what is wrong.
Try this;
<?php
// Connect with user
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
// Select database
mysql_select_db("disertation", $con);
// Run query
$results = mysql_query("SELECT `name` FROM `user_parent`;") or die (mysql_error());
// Check for no results
if (mysql_num_rows($results) == 0)
{
echo 'There are no options for you to select.';
}
else
{
// If results, loop them.
// If the names are user input, make sure they're displayed in non-raw form
echo '<select name="name">
<option value="name">Select one</option>';
while($row = mysql_fetch_assoc($results))
{
$name = htmlentities($row['name'], ENT_QUOTES, "UTF-8");
echo '<option value=" ' . $name . ' ">' . $name . '</option>';
}
echo '</select>';
}
Will edit with a mysqli_ solution, if that is an option for you, since mysql_ is deprecated and will be dropped from PHP support, sooner or later.
MySQLi solution;
<?php
// Connect to database;
$mysqli = new mysqli("localhost", "my_user", "my_password", "data_base");
if (mysqli_connect_errno())
{
die("Connect failed: " . mysqli_connect_error());
}
$result = $mysqli->query("SELECT `name` FROM `user_parent`");
if ($result->num_rows > 0)
{
echo '<select name="name">
<option value="name">Select one</option>';
while($row = $result->fetch_assoc)
{
$name = htmlentities($row['name'], ENT_QUOTES, "UTF-8");
echo '<option value=" ' . $name . ' ">' . $name . '</option>';
}
echo '</select>';
$result->close();
}
else
{
echo 'There are no options for you to select.';
}

Related

Getting Selectbox values from the database using PHP and mysqli

I want to pick up peoples names from a phpmyadmin database and place them in a HTML select box, when the user picks a name from the select box it should display the detail from the database for that person in a table. I can't seem to get this to work, I can get the names to pick up from the database and display in a select box but when you click on the name it seems to bring up every record in the database rather than just the one for that person. I am using mysql rather than mysql. Here is my code
This is my back end stuff
<?php
$conn = mysqli_connect("localhost", "root", "root") or die ("No connection");
mysqli_select_db($conn, "flat") or die("db will not open");
$query = "select FlatCode, Address from FLAT";
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'><tr><th>modulecode</th><th>studentnum</th></tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
}
echo "</table>";
mysqli_close($conn);
?>
this is my front end stuff
<font size="4"> Choose an Owner Name</font><br><br>
<form action="flat.php" method="post">
<select name="name">
<?php
$con = mysqli_connect("localhost", "root", "root") or die ("No connection");
mysqli_select_db($con , "flat") or die ("db will not open");
$query = "SELECT distinct OwnerName, FlatCode, Address from FLAT";
/*$query= $_POST ("name")
function change_guery($query)
mysqli_use_result*/
$result = mysqli_query($con, $query) or die("Invalid query");
while($rows = mysqli_fetch_array($result))
{
echo "<option value=\"" . $rows[0] . "\">" . $rows[0] . "</option>";
}
echo "</select>";
mysqli_close($con);
?>
<input type="submit" value="Submit Value">
</form></body></html>
There is a problem in your flat.php code. You are posting the the info correctly via form but you forgot to receive it via $_POST in flat.php.
See the following code and comments in it, it should work -
<?php
$n = $_POST["name"];//we receive the name passed by the form
$conn = mysqli_connect("localhost", "root", "root") or die ("No connection");
mysqli_select_db($conn, "flat") or die("db will not open");
$query = "select FlatCode, Address from FLAT WHERE `OwnerName` = '$n' LIMIT 1";//see the changes here
$result = mysqli_query($conn, $query) or die("Invalid query");
echo "<table border='1'><tr><th>modulecode</th><th>studentnum</th></tr>";
$row = mysqli_fetch_array($result);
//as the result will return 1 row only so we dont need while loop here
echo "<tr><td>" . $row[0] . "</td><td>" . $row[1] . "</td></tr>";
echo "</table>";
mysqli_free_result($result);//dont forget to free result
mysqli_close($conn);
?>

Extract from database to form select

Working on a project where I am going to extract from my database and show the pool name in a form select. But very unsure how to go further than this.
$con=mysqli_connect("localhost","root","","nih_bw");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "Select name from pools";
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
}
mysqli_close($con);
You can do something like this:
<?php
$con=mysqli_connect("localhost","root","","nih_bw");
// Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"Select name from pools");
echo "<select name='mypool'>";
$default_name = "foo_bar";
while($row = mysqli_fetch_array($result)){
$opt_name = $row['name'];
$str_selected = "";
if($opt_name == $default_name){
$str_selected = "selected";
}
echo "<option value='".$opt_name."' ".$str_selected." >" . $opt_name. "</option>";
}
echo "</select>";
mysqli_close($con);
?>
You can see an introductory article here:http://www.w3schools.com/Php/php_mysql_select.asp
Hope this helps.
Try using your query like this:
<select name="batch">
<option value="">Select One</option>
<?php
$pd=$dbh->prepare("SELECT * FROM `pools`");
$pd->execute();
foreach($pd->fetchAll() as $rw) :
?>
<option value="<?php echo $rw['id'];?>"><?php echo $rt['name'];?></option>
<?php endforeach; ?>
</select>
It is in pdo, but you will get my logic.
I think this will work for you. (Code is not tested)
<?php
$record = array();
$con=mysqli_connect("localhost","root","","nih_bw");
// Check connection
if (mysqli_connect_errno($con)){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "Select name from pools";
if(!$result = mysql_query($sql,$con)){
die('There was an error running the query [' . $db->error . ']');
}
else{
while($row = mysql_fetch_assoc($result)){
$record[] = $row;
}
}
mysqli_close($con);
?>
<select>
<?php
foreach($record as $value){
echo "<option>".$value."</option>";
}
?>
</select>

PHP-mysql_fetch_array return nothing

I've trying to display values from mysql but it return any empty page. The connection is fine but it does not fetch the data from mysql. I tried all the answers from the similar questions asked. But nothing helped. Can somebody please help me? This is the code
$con= mysql_connect($host, $username, $pwd);
if(!$con)
die("not connected". mysql_errno());
echo(Connected);
mysql_select_db("info",$con);
$query="select * from people";
$result= mysql_query($query,$con) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['id']. " - ". $row['people_name'];
echo "<br />";
}
Try to check if your db user,password are correct! I test the code above :
<?php $con=mysqli_connect("localhost","root","","test"); // Check connection
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM people");
while($row = mysqli_fetch_array($result)) {
echo $row['id'] . " -- " . $row['people_name']; echo "<br>";
}
?>
and give me the result without error: 10 -- JOHN 11 -- PRADEEP
I just change mysql_connect to mysqli_connect add in $con= mysql_connect($host, $username, $pwd); a dbname. and $con become $con= mysqli_connect($host, $username, $pwd,$dbname); I use mysqli_query instead of mysql_query. Here is a stackQuestion for the mysql vs mysqli in php which can explain you the difference.
Try this
<?php
$con= mysql_connect('hostname', 'username', 'password');
if(!$con)
die("not connected". mysql_errno());
echo("Connected");
mysql_select_db("test",$con);
$query="select * from tabale_name";
$result= mysql_query($query,$con) or die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo $row['id']. " - ". $row['name'];
echo "<br />";
}
?>
check this
<?php
$con=mysqli_connect("hostname","username","password","info");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM people");
while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['people_name'];
echo "<br>";
}
?>
OR
<?php
$con=mysqli_connect("hostname","username","password");
// Check connection
if ($con)
{
echo "connected to db";
}
else
{
echo "not connected to db";
}
$db_selected = mysql_select_db("info", $con);
if (!$db_selected)
{
die ("Can\'t use info: " . mysql_error());
}
$result = mysqli_query("SELECT * FROM people");
while($row = mysqli_fetch_array($result))
{
echo $row['id'] . " " . $row['people_name'];
echo "<br>";
}
?>

Is it possible to have a pull down menu to have an item selected in its list show if database already has information in it?

Version 4:
I have taken away the pull down menu for now, I just want the info to be posting correctly.
As it shows with the first line fab1 shows #2, in the second line it shows 1, --None-- instead of 2, Andy Khal. If anyone can figure out why, it be appreciated. I've done about as much as I can to figure this out and I'm lost.
<?php
// Connect to the database.
require_once('tb/connectvars.php');
$dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
die("MySQL failed to connect: " . mysqli_connect_error());
}
// Create the SQL query
$testbed = "SELECT * FROM testbed";
$user = "SELECT * FROM user";
// Execute the SQL query and store the result set in
// the $result variable.
$testbed = mysqli_query($dbc, $testbed) or die("Failed to execute query on tesbed table: " . mysqli_error($dbc));
$user = mysqli_query($dbc, $user) or die("Failed to execute query on user table: " . mysqli_error($dbc));
// Read the results.
$row = mysqli_fetch_assoc($testbed);
if(!$row)
{
echo 'Query failed<br />';
}
else
{
echo "Query for Testbed Fabricator is : " . $row["fab1"] . "<br />";
}
$row = mysqli_fetch_assoc($user);
if(!$row)
{
echo 'Query for Testbed Fabricator failed<br />';
}
else
{
echo "Query for User ID # is : " . $row["userid"], $row["user"] . "<br />";
}
// Free the result set.
mysqli_free_result($testbed);
mysqli_free_result($user);
?>
Yes it is. You can specify the selected value with the selected keyword as a html attribute.
<option value="Username" selected>Username</option>
That makes this:
while($row = $result->fetch_assoc())
{
$user = $row['user'];
echo '<option value="' . $user . '"';
if($user is known)
{
echo ' selected';
}
echo '>' . $user . '</option>\n';
}
Update
In this snipped $choosen is the selected user's name.
echo'<div id="fab1">';
$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$mysqli->select_db('user');
$result = $mysqli->query("SELECT * FROM user");
echo "<select name='fab1'>\n";
while($row = $result->fetch_assoc())
{
echo '<option value="' . $row['user'] . '"';
if($row['user'] == $choosen)
{
echo ' selected';
}
echo '>' . $row['user'] . '</option>\n';
}
echo "</select>\n";
echo '</div>';

how to write text in textbox from database in php

I have a form where I am getting values from previous page in $GET. I want to fetch around 3 different values from database and display them in textbox. How will I do it? Following is my code for getting data from database.
<?php
require_once('config.php');
$id = $_GET['id'];
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
$query = "select question,price,sequence from questions where status = 1 and qid =".$id;
//echo $query;
$result=mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$num_rows = mysql_num_rows($result);
if($num_rows==0) {
echo '<center><font color="red"><b>No record found!!</b></font></center>';
}
else {
$row = mysql_fetch_array($result);
echo $row['question'];
echo $row['sequence'];
echo $row['price'];
}
?>
Thanks
Pankaj
<textarea><?php echo htmlentites($row['question']);?></textarea>
or
<input type="text" value="<?php echo htmlentites($row['question']);?>" />
Depending on your fancy.

Categories