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();
?>
Related
I know that this question has been on multiple S.O. forums, but after reviewing, I seem to not be able to get the data elements in my phpmyadmin to appear in my html select. I am new to php, so therefore I am not very good at the fundamentals. Can anyone take a look at my code and tell me whats wrong with it? I am not getting any errors, just nothing in my html select.
Code:
<?php
$con = mysqli_connect('localhost','root','','Lab2_Database');
if($con-> connect_error) {
die("Connection Failed:".$con-> connect_error);
}
?>
<h1 id="header">Welcome to The Flight Club WebSite</h1>
<br>
<p>Select a Flight by Flight Number:</p>
<form>
<select>
<option value="0">Flight Number</option>
<?php
$sql = "SELECT flightNumber FROM Flight";
$result = $con-> query($sql);
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['flightNumber'])?>" >
<?php echo($row['flightNumber']) ?>
</option>
<?php
}
?>
</select>
</form>
</body>
</html>
$result = $con-> query($sql);
while($row = mysql_fetch_assoc($get))
{
?>
<option value = "<?php echo($row['flightNumber'])?>" >
<?php echo($row['flightNumber']) ?>
</option>
<?php
}
change with
$result = $con-> query($sql);
while($row = mysql_fetch_assoc($result))
{
?>
<option value = "<?php echo($row['flightNumber'])?>" >
<?php echo($row['flightNumber']) ?>
</option>
<?php
}
variable $get is not defined i think
you are using mysql with mysqli object
$result = $con-> query($sql);
while($row = mysql_fetch_assoc($get))
{
?>
change this to
$result = $con-> query($sql);
while($row = $result->fetch_assoc())
{
?>
http://php.net/manual/en/mysqli-result.fetch-assoc.php
I have two input text fields where user has to specify the begin and end of the fly.
<input type="text" name="start" placeholder="Start destination">
<input type="text" name="end" placeholder="End destination">
I would like to change that and give user to chose start and end destination from database.
<select>
<option value="$id">$name</option>
</select>
I know how to get done if i read database and input values manually, but i know its posible if page loads and execute my SELECT QUERY.
So i have to create dropdown list and fill that with a values from database.
This dropdown list has to be filled when the page load.
Some idea for this ???
I am working with php.
Thank you in advance !!
EDIT : I get done this only with php.
<?php
$db_host = "localhost";
$db_username = "root";
$db_password = "";
$db_name = "flights";
$conn = mysql_connect("$db_host","$db_username","$db_password") or die ("no conn");
#mysql_select_db("$db_name") or die ("no database");
if ($conn = true) {
// echo "";
}
//cyrilic
$sql = "SET NAMES 'utf8'";
mysql_query($sql);
//query for end
$sql="SELECT Distinct end from flights_table;";
$result=mysql_query($sql);
echo "<select name=\"city\">";
echo "<option>end destination</option>";
while ($row = mysql_fetch_array($result))
{
echo "<option value='".$row['end']."'>".$row['end']." </option>";
}
echo "</select>";
?>
This php fires when page loads. Those select options i have putted in a form, and when form is submited, it fires php itself. I am getting selected options this way :
$startfly=$_POST['end'];
I am doing this for starting the flight :)
Thank you guys !
Try this :
At the top of page include your database connection file :
<?php
require "connection.php";
?>
Then :
<?php
$selectStart = "Start : <select name='start'>";
$selectEnd = "End : <select name='end'>";
$query = mysql_query("SELECT * FROM someTable ORDER BY dateField ASC");
if(mysql_num_rows($query) > 0)
{
while($row = mysql_fetch_assoc($query))
{
$selectStart .= "<option value='".$row['startItem']."'>".$row['startItemName']."</option>";
$selectEnd .= "<option value='".$row['endItem']."'>".$row['endItemName']."</option>";
}
}
$selectStart = "</select>";
$selectEnd = "</select>";
?>
In your HTML :
<form action='destinationPage.php' method='post'>
<?php
echo $selectStart;
echo $selectEnd;
?>
<input type='submit' value='Submit' />
</form>
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 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>";