How to populate a dropdown menu in ahtml form - php

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.

Related

How to fetch data from database table on PHP page

I have created one IMS in that I am trying to fetch data from one table from the database and display it in drop-down form to another page.
In the database, I have created one table named a party in that table one column named party_name is available and I have to fetch that column data to my order page. Below is my Code. If anyone knows a solution than please help.
<select name="party[]" style="width:100%;" required>
<?php
$result=mysql_query("SELECT * FROM partys");
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['party_name'];?></option>
<?php
}
?>
</select>
Firstly: mysql extension is deprecated, you should use at least mysqli_*:
Secondly: try the below example, replacing the database connection string variables with your database credentials:
<select name="party[]" style="width:100%;" required>
<option value="">-- Please select --</option>
<?php
$dbc = mysqli_connect('localhost', 'userName', 'password', 'databaseName')
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM partys";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['id'];?>"><?php echo $row['party_name'];?></option>
<?php } ?>
</select>

PHP/ MySQL select box and input

I begin to learn PHP because VBA is not enough.
And today I ask you to help.
I have Select box, which takes data from MySQL.
I have Input to which I would like to enter the data from the second column, the same table with that take the data to a select box and do not know how I do it.
If you want to add value from variable to input field you can do next
//$var you get from query from this your mysql table
<input type="text" name="somename" value="<?php echo $var['second_column']; ?>" id="someid">
are you asking for how to put data into a selectbox from database ?? If so, you can use this..
<select name="country">
<option value="">Select</option>
<?php
$countriesQuery=mysqli_query($conn,"SELECT id,name FROM countries");
while($countries=mysqli_fetch_assoc($countriesQuery))
{
echo "<option value='$countries[id]'>$countries[name]</option>";
}
?>
</select>
<select name="country">
<option value="">Select</option>
<?php
$countriesQuery=mysqli_query($conn,"SELECT id,name FROM countries");
while($countries=mysqli_fetch_assoc($countriesQuery))
{
echo "<option value='".$countries[id]."'>".$countries[name]." </option>";
}
?>
</select>
Hope this helps
<?php
$mysqli= new mysqli("localhost", "root", "", "db");
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$result=$mysqli->query("select name from table");
/* name is your second field*/
?>
<select name="">
<?php
while($res=$result->fetch_array())
{?>
<option value="<?php echo $res[0]; ?>"><?php echo $res[0]; ?></option>
<?php
}
?>
</select>

PHP option value based on database table

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();
?>

how to set the selected value tag <select> html from database in php?

I'm trying to create a drop down menu that will select a value that is stored in the database. here's the code :
require 'koneksi.php';
$sql_select = "SELECT * FROM supplier";
$hasil = mysql_query($sql_select);
if(!$hasil) {
echo "data supplier not found ".mysql_error();
}
$id = $_GET["id"];
$hasil2 = mysql_query("SELECT * FROM brg_supplier WHERE id_brg=".$id);
$data = mysql_fetch_array($hasil2);
if($hasil2) {
$supplier = $data['nama_supplier'];
}
<select name="supplier">
<option value="">---pilih supplier---</option>
<?php
while($baris = mysql_fetch_array($hasil)){
?>
<option value="<?php $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) echo 'selected="selected"'; ?> > <?php echo $baris['nama_supplier']; ?> </option>;
<?php }?>
</select>
the problem is my code creates a dropdown with nothing selected. here's the screenshot : link
i've tried all the solutions in the stackoverflow. but the dropdown value still nothing selected. i know that it has to be something simple that i am missing but seriously i cannot figure it out. please anyone help, thanks!
I think the problem lies in this line:
<option value="<?php $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) echo 'selected="selected"'; ?> > <?php echo $baris['nama_supplier']; ?> </option>;
You're missing an echo and it looks funny :/
Try instead:
<option <?php $val=$baris['nama_supplier']; echo "value='$val'"; if($supplier==$val) echo "selected='selected'>";echo $val;?> </option>;
Try this way..
$sel="select f.*,c.category from final f, category c where f.category_id=c.id and f.id='$id'";
$data=mysql_query($sel);
$res=mysql_fetch_assoc($data);
<select name="cat">
<?php
$sql = mysql_query("SELECT * FROM category");
while ($row = mysql_fetch_array($sql)){
if($row['id'] == $res['category_id']){
echo '<option value="'.$row['id'].'" selected="selected">'.$row['category'].'</option>';
}else{
echo '<option value="'.$row['id'].'">'.$row['category'].'</option>';
}
}
?>
</select>
Try this out
require 'koneksi.php';
$sql_select = "SELECT * FROM supplier";
$hasil = mysql_query($sql_select);
if(!$hasil) {
echo "data supplier not found ".mysql_error();
}
$id = $_GET["id"];
$hasil2 = mysql_query("SELECT * FROM brg_supplier WHERE id_brg=".$id);
$data = mysql_fetch_array($hasil2);
if(mysql_num_rows($hasil2) > 0) {
$supplier = $data['nama_supplier'];
}
<select name="supplier">
<option value="">---pilih supplier---</option>
<?php
while($baris = mysql_fetch_array($hasil)){
?>
<option value="<?php echo $baris['nama_supplier'] ?>" <?php if ($supplier==$baris['nama_supplier']) {echo 'selected="selected"';} ?> > <?php echo $baris['nama_supplier']; ?> </option>;
<?php }?>
</select>
<option value="<?php $baris['nama_supplier'] ?>
should be
<option value="<?php echo $baris['nama_supplier'] ?>
I spent some time trying to find the best solution for this, and came up with a tiny little jQuery code.
First of all you should be using PDO or mysqli instead of mysql, since it's deprecated. Let's assume you've fixed that.
Inside the <form> tag, add an <input type="hidden"/> so that it can storage your database value, for example:
HTML
<form>
<input id="valueFromDatabase" type="hidden" value="<?php echo $stringFromDB ?>"/>
</form>
Note: in this case, $stringFromDB is a variable that holds your query's return from DB.
So now we have the value of our database inside our HTML code. Now we just need to check if any of the options inside the <select> tag is equal to this value. We'll be doing it with jQuery:
jQuery
$( document ).ready(function() {
$('option').each(function(){
if (this.value == $('#valueFromDatabase').val()){
this.setAttribute('selected', 'selected');
}
});
});
What's happening here? We are telling to jQuery to analyze all the <option> tags in the HTML and compare its value with our value from database; if its equal, we add the selected attribute to the equivalent <option>.
You can it working here (used a calendar example).
Hope that helps!

Display Mysql table field values in Select box

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>";

Categories