I want to display the Mysql table Filed values in selectbox. I tried the following code to display.
But it normally display the specified field values in echo function and not in select box. I don't know where I mistake.
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");
while($row = mysql_fetch_assoc($get))
{
echo ($row['Emp_id']."<br/>");
}
<html>
<body>
<form>
<select>
<option value = "<?php echo($row['Emp_id'])?>" ><?php echo($row['Emp_id']) ?></option>
</select>
</form>
</body>
</html>
Also the field values must be display in ascending order. How to achieve..
<?php
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee ORDER BY Emp_id ASC");
$option = '';
while($row = mysql_fetch_assoc($get))
{
$option .= '<option value = "'.$row['Emp_id'].'">'.$row['Emp_id'].'</option>';
}
?>
<html>
<body>
<form>
<select>
<?php echo $option; ?>
</select>
</form>
</body>
</html>
PS : On a sidenote, please stop using mysql_* functions. Take a look at this thread for the reasons.
You can easily do it like this
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");
<html>
<body>
<form>
<select>
<option value="0">Please Select</option>
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['Emp_id'])?>" >
<?php echo($row['Emp_id']) ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
You have to use while loop to display option in select box. try this ...
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee order by Emp_id");
<html>
<body>
<form>
<select>
<?php
while($row = mysql_fetch_assoc($get))
{
?>
<option value="<?php echo $row['Emp_id']; ?>"><?php echo $row['Emp_id']; ?></option>
<?php
}
?>
</select>
</form>
</body>
</html>
<?php
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$get=mysql_query("SELECT Emp_id FROM Employee");
?>
<html>
<body>
<form>
<select>
<?php
while($row = mysql_fetch_assoc($get)){?>
<option value = "<?php echo($row['Emp_id'])?>" ></option>
<?php } ?>
</select>
</form>
</body>
<?php
$con = mysql_connect("localhost","root","root");
$db = mysql_select_db("Time_sheet",$con);
$res=mysql_query("SELECT Emp_id FROM Employee");
?>
<html>
<body>
<form>
<select>
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value=" '.$row['id'].' "> '.$row['name'].' </option>';
}
?>
</select>
<form>
</body>
</html>
There a few tips to offer that will condense the code block for this task -- too many to just comment under the accepted answer.
Tested Code:
if (!$con = new mysqli("localhost", "root", "root", "Time_sheet")) {
echo "Database Connection Error: " , $con->connect_error; // don't show actual error in "production" stage
} elseif (!$result = $con->query("SELECT Emp_id FROM Employee ORDER BY Emp_id")) {
echo "Syntax Error: " , $con->error; // don't show actual error in "production" stage
} else {
echo "<select>";
foreach ($result as $row) {
echo "<option>{$row['Emp_id']}</option>";
}
echo "</select>";
}
The if line is both declaring $con and checking it for a falsey return value in one step.
Never provide the raw connection or query errors to your users. It is okay during development, but you don't want strangers to have access to critical/informative errors that your server will provide. This is a basic best practice for security.
The elseif line is both declaring $result and checking it for a falsey return value in one step.
The else block will process the zero or more rows of data that were generated as a result of the successful SELECT query.
The mysqli result is "traversable" which means you can iterate it using foreach() and enjoy direct access to the row data via associative keys. PHP Manual Reference Another StackOverflow Post
When writing an array element into a literal string via interpolation, it is good practice (though not always necessary) to wrap the element in curly braces. This will often trigger helpful highlighting in IDEs and ensure that the characters that follow the array are not accidentally coupled to the variable name itself.
You ONLY need to write a value attribute inside of the <option> tag IF the value is different from text between the opening and closing tags (<option>the text in here</option>). Form submissions and javascript implementations will all work the same if you omit the redundant value attribute.
If you DO wish to submit a different value in the select field rather than the text, here is what the syntax can look like:
echo "<option value=\"{$row['Emp_id']}\">{$row['Emp_name']}</option>";
If you want to write a selected attribute on one of the options based on a pre-existing variable (e.g. $selected_id), it can look like this:
echo "<option" , ($row['Emp_id'] == $selected_id ? " selected" : "") , ">{$row['Emp_name']}</option>";
If you wanted to combine the two previous processes, it can look like this:
echo "<option value=\"{$row['Emp_id']}\"" , ($row['Emp_id'] == $selected_id ? " selected" : "") , ">{$row['Emp_name']}</option>";
Related
My problem now:
once I echo the value from the database its woking good. but when I submit the form I got an empty value of the selected option.
Can any one help. I tried to used {} in he value code but it did not work.
What I want :
Set the the value of the selected option as it is on the database to insert it into another table.
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="" selected>--select-- </option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if ($num_rows > 0) {
while($row = mysql_fetch_array($result)){
echo '<option value="'.$row['centerName'].'">'.$row['centerName'].'</option>';
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
Try this
<select class="form-control" name="CenterTO" id="CenterTO">
<option value="0" selected>--select--</option>
<?php
require("inc/DB.php");
$query = "SELECT centerName FROM jeCenter";
$result = mysql_query($query);
$count = count($result);
if (!empty($count)) {
while($row = mysql_fetch_array($result))
{
$name = $row['centerName'];
echo "<option value='$name'> $name </option>";
}
} else {
echo '<option>No data</option>';
}
mysql_close();
?>
</select>
You will have to "expand" your select query to include the ID of the row, and then instead of $row['centerName'] use $row['id'] (or what your ID column is named) in the value argument of the option element, and not the 'centerName'. If I understood correctly what you want, this should be it.
Edit: And do switch to mysqli_, mysql_ has been deprecated.
try to write like this:
echo '<option value="',$row["centerName"],'">',$row["centerName"],'</option>';
Warning:
Please don't use the mysql_ database extensions, they were deprecated in PHP 5.5.0 and were removed in PHP 7.0.0. Use mysqli or PDO extensions instead.
Solution
I recreated your issue and enhanced your code using mysqli extensions, and it's working fine. Take a look at the following code,
<?php
if(isset($_POST['submit'])){
// display submitted option
echo $_POST['CenterTO'];
}
?>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbName = "stackoverflow";
// Open a new connection to the MySQL server
$connection = new mysqli($host, $username, $password, $dbName);
// Check connection
if($connection->connect_errno){
// error
die('Connect Error: ' . $connection->connect_error);
}
// Execute query
$result_set = $connection->query("SELECT centerName FROM jeCenter");
?>
<form action="form_page.php" method="POST">
<select name="CenterTO">
<option value="" selected>--select-- </option>
<?php
// Check if number of rows is greater than zero or not
if($result_set->num_rows > 0){
// Loop through each record
while($row = $result_set->fetch_assoc()){
?>
<option value="<?php echo $row['centerName']; ?>"><?php echo $row['centerName']; ?></option>
<?php
}
}else{
?>
<option value="none">No data</option>
<?php
}
?>
</select>
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
<?php
// Close connection
$connection->close();
?>
can anybody post an code for option list which can retrieve data dynamically from database, and once user selects from option list a record, that record must post it ($_POST) to database.. !!
ive tried this, it retrieves records from db, but not posting it :
<?php
require_once "db.php";
if (isset($_POST['a_id']) {
$a = $_POST ['a_id'];
$sql = "INSERT INTO projektet
VALUES ('$a')";
mysql_query($sql);
}
HERE IS THE PART SEEMS NOT WORKING :
<form method="post">
<select name="a_id">
<?php
$host="localhost";
$username = 'root';
$password = "";
$con = mysql_connect($host,$username,$password);
mysql_select_db('naho',$con);
// Checking connection
if (!$con){
echo ("Failed to connect to MySQL:. " .mysql_error($con));
}
else {
echo("db connect");
}
$result = mysql_query("SELECT * from `arqitekti`");
if($result == FALSE) {
die(mysql_error()); // TODO: better error handling
}
while($row=mysql_fetch_array($result)){
?>
<option value="<?php '.row[a_id];'?>"><?php echo $row["a_emri"];?></option>
<?php }
?>
</select>
<input type="submit" value="submit"/>
</form>
<option value="<?php '.row[a_id];'?>"><?php echo $row["a_emri"];?></option>
This line looks strange... Shouldn't it be:
<option value="<?php echo $row[a_id]; ?>"><?php echo $row["a_emri"];?></option>
I think that your code is POSTing, but it wasn't getting any value because of the value declaration on the options of the select. After that change it should work.
PS: If your POST code isn't in the same page as your HTML, it's <form method="POST" action="YOUR_PAGE">, not only <form method="POST">.
I'm trying to populate a dropdown field inside a html form, but the field doesn't show any value, only a blank one.
I'm trying the following code:
<select name="Select" class="textfields" id="prods">
<option id="0">--Producto--</option>
<?php
require("conectdb.php");
$allproducts = mysql_query("SELECT * FROM Productos");
while ($viewallproducts = mysql_fetch_array($allproducts)){
?>
<option id="<?php echo $viewallproducts["ID"];?>"><?php echo $viewallproducts["CODIGO"];?></option>
<?php } ?>
</select>
I have changed the quotes and ;... But still nothing, here is the code of connection to the Database (conectdb.php):
<?php
$con=mysqli_connect("localhost","xxxxxx","xxxxxx","xxxxxx");
// Check connection
if (mysqli_connect_errno())
echo "Failed to connect to MySQL: " . mysqli_connect_errno();
mysqli_close($con);
?>
It seems to be a problem of the database connection, Im trying now the following code to see what happens:
<?php
$username = "xxxxx";
$password = "xxxxx";
$hostname = "xxxx";
$dbhandle = mysql_connect($hostname, $username, $password)
or die("Unable to connect to MySQL");
echo "Connected to MySQL<br>";
$allproducts = mysql_query("SELECT * FROM PRODUCTOS");
while ($viewallproducts = mysql_fetch_array($allproducts)){
echo ($viewallproducts);
}
?>
But, on this php, I receive the following error:
Warning: mysql:fetch_array() expects parameter 1 to be resource.
I have also tried with mysql_fetch_row() and gives me the same error.
1) You have error in require line(put file name inside quotation )
2) you don't put value attribute in option.
Try this:
<select name="Select" class="textfields" id="prods">
<option id="0" value="o">--Producto--</option>
<?php
require("conectdb.php");
$allproducts = mysql_query("SELECT * FROM Productos");
while ($viewallproducts = mysql_fetch_array($allproducts)){
?>
<option id="<?php echo $viewallproducts['ID'];?>" value="<?php echo $viewallproducts['ID'];?>"><?php echo $viewallproducts['DESCRIPCION'];?></option>
<?php } ?>
</select>
I think you made a mistake because you think ID in html is ID in database. You need to use "value" attribute for option
chance this line
<option id="<?php echo $viewallproducts['ID'];?>"><?php echo $viewallproducts['DESCRIPCION'];?></option>
to
<option value="<?php echo $viewallproducts['ID'];?>"><?php echo $viewallproducts['DESCRIPCION'];?></option>
You have also forget about:
require argument in ''
; after require
Function to get rows should be 'mysql_fetch_row' instead of 'mysql_fetch_array'
I would also suggest you using better DB engine for example PDO or MySQLi because MySQL_* functions are depracated.
Code formatted:
<select name="Select" class="textfields" id="prods">
<option value="0">--Producto--</option>
<?php
require('conectdb.php'); // be sure that file exist you forgot about '' and ;
$allproducts = mysql_query("SELECT * FROM `Productos`");
while ($viewallproducts = mysql_fetch_row($allproducts))
echo '<option value="'.$viewallproducts['ID'].'">'.$viewallproducts['DESCRIPCION'].'</option>';
?>
</select>
You forget to put the semicolon after the line
require(conectdb.php)
And you should add a quotation
require("conectdb.php");
Maybe is that
Some edit on your code:
<select name="Select" class="textfields" id="prods">
<option id="0">--Producto--</option>
<?
require("conectdb.php");
$allproducts = mysql_query("SELECT * FROM Productos")
or die(mysql_error());
while ($viewallproducts = mysql_fetch_assoc($allproducts)){
?>
<option id="<?=$viewallproducts['ID'];?>" value="<?=$viewallproducts['ID'];?>">
<?=$viewallproducts['DESCRIPTION'];?></option>
<?php } ?>
</select>
You should use mysql_fetch_assoc instead of mysql_fetch_array. You should also check if the sql query succeed first.
I can see the query returning results, but I can't seem to be able to put them into a html dropdown box. Also, the dropdown box has just as many entries as the query returns, but THEY ARE ALL WHITE SPACES. HOWEVER, the page source shows correct option values such as
<option value="3 John"></option>
<option value="Jude"></option>
<option value="Revelation"></option>
Can somebody help me out? Why dont they actually show in the dropdown box?
<html>
<?php
//Connect to the database
$mysqli = new mysqli("localhost", "root", "", "bible");
//Return an error if we have a connection issue
if ($mysqli->connect_error) {
die('Connect Error (' . $mysqli->connect_errno . ') '
. $mysqli->connect_error);
}
//Query the database for the results we want
$query = $mysqli->query("select distinct bname as Name from kjv limit 1");
//Create an array of objects for each returned row
while($array[] = $query->fetch_object());
array_pop($array);
//Print out the array results
print_r($array);
?>
<h3>Dropdown Demo Starts Here</h3>
<select name="the_name">
<?php foreach($array as $option) : ?>
<option value="<?php echo $option->Name; ?>"></option>
</select>
<?php endforeach; ?>
Try This
<select name="the_name">
<?php foreach($array as $option) : ?>
<option value="<?php echo $option['Name']; ?>"><?php echo $option['Name']; ?></option>
<?php endforeach; ?>
</select>
After the query is executed use the while loop to add the options to select
$query = $mysqli->query("select distinct bname as Name from kjv limit 1"); ?>
<select>
<?php while($option = $query->fetch_object()){ ?>
<option><?php echo $option->Name; ?></option>
<?php } ?>
</select>
Not sure what the array_pop is doing in the code
AS TIM WAX SAID THIS IS THE SOLUTION
$query = $mysqli->query("select distinct bname as Name from kjv limit 1"); ?>
<select>
<?php while($option = $query->fetch_object()){ ?>
<option><?php echo $option->Name; ?></option>
<?php } ?>
</select>
<select name="the_name">
<?php foreach($array as $option) : ?>
<option value="<?php echo $option->Name; ?>"></option>
<?php endforeach; ?>
</select>
You ended your loop in a way that it also create <select> tag again and again. Change it and try again. I don't know much about .php but it could be a problem in showing your dropdown box.
here is mine .. im a beginner but it works for me,
$query = $mysqli->query("SELECT * FROM `student_type_db`"); //table of student type
echo "<select>";
while($row = $query->fetch_array()){
echo "<option>";
echo $row['student_type'] . " - " . $row['student_description'];
echo "</option>";
}
echo "</select>";
// student type = 1 | student description = regular
// output : 1 - regular
I have a Query that looks something like this (I know its vulnerable to sql injection, its just a template):
$db = mysql_connect("host","un", "pw");
mysql_select_db("db", $db);
$sql = "SELECT *"
. " FROM Student" ;
$result = mysql_query($sql);
$students = mysql_fetch_assoc($result);
$numRows = mysql_num_rows($result);
Then I have this form:
<form name="form" id="form" method="post" action="page">
<select name="student" id="student">
<?
for ($i=0;$i<=$numRows;$i++){
echo "<option>" . $students['StudentID'] . "</option>";
}
?>
<option selected="selected">Please select a student</option>
</select>
This should print something like a drop down box with all the values from the table as items. However, I get a drop down box with 6 of the same items, in this case, I get 6 student Id's, but they are all the same ID. I have six students in the db, and I would like to display each of them as an option. What am I doing wrong?
TIA
Have a look at the examples of mysql_fetch_assoc. It will only return one record. In order to get all of them, you have to use it in a loop, e.g.:
$students = array();
while(($student = mysql_fetch_assoc($result))) {
$students[] = student;
}
and later:
<?php foreach($students as $student): ?>
<option><?php echo $student['StudentID']; ?></option>
<?php endforeach; ?>
or with a for loop (but it is not necessary if you don't need a counter):
<?php for($i = 0; $i < numRows; $i++): ?>
<option><?php echo $students[$i]['StudentID']; ?></option>
<?php endfor; ?>
(Note: I use the alternative syntax for control structures which imho is much more readable when mixing HTML and PHP)