Right now I have a working solution for populating an HTML <select>/<option>-dropdown with the content through PHP/MYSQLI from my database: listoption.
The database:
DATABASE NAME:
# listoption
TABLES:
# ID INT(11) *Primary AI
# listoption_item VARCHAR(255)
Here's the other code (not the mysqli connect but everything afterwards..)
<?php
$result = $mysqli->query("select * from listoption");
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
echo '<option value="'.$listoption_item.'">'.$listoption_item.'</option>';
}
echo "</select>";
?>
But the problem is now that I want to have one of these options that are populated through that query to be selected. And the option to be selected should be determed by a parameter in the URL, for example: index.php?id=1.
So now I need to somehow add a IF/ELSE and a $_GET['id']; into the code to make it identify if the ID from the database is the same as the populated item and then set it to selected.
Any idéas? Thanks!
You can do that like given below:
<?php
$result = $mysqli->query("select * from listoption");
$id = ($_GET['id'])? $_GET['id'] : '';
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
$sel = ($id == $row['id'])? 'selected="selected"':'';
echo '<option value="'.$listoption_item.'" '.$sel.'>'.$listoption_item.'</option>'; // $sel will deside when to set `selected`
}
echo "</select>";
?>
You can rewrite the code as follows:
<?php
$id = $_GET['id'];
$select = "";
$result = $mysqli->query("select * from listoption");
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$row_id = $row['ID'];
if($row_id == $id){
$select = "selected";
}
$listoption_item = $row['listoption_item'];
echo '<option value="'.$listoption_item.'" selected="'.$select.'">'.$listoption_item.'</option>';
}
echo "</select>";
?>
Use the following code:-
<?php
$selectedId = isset($_GET['id'])?$_GET['id']:0;
$result = $mysqli->query("select * from listoption");
echo "<select id='list' name='list'>";
while ($row = $result->fetch_assoc()) {
$listoption_item = $row['listoption_item'];
echo '<option value="'.$listoption_item.' .(($selectedId>0)?:" selected ":"").'">'.$listoption_item.'</option>';
}
echo "</select>";
?>
Related
I already try many ways but the value didn't show in dropdown list
Here, this is my code. can you suggest me anything that i was wrong
<?php
$result = mysqli_query($con,"SELECT * FROM project");
if( mysqli_num_rows( $result )==0){
echo "<tr><td>No Rows Returned</td></tr>";
}else{
$row = mysqli_fetch_assoc( $result );
$pos = 0;
echo "<select name=Pname >";
while($pos <= count ($row)){
echo "<option value="$row["project_no"]">"$row["project_name"]"</option>";
$pos++;
}
echo "</select>";?>
And i write as .php file. Thanks for your help.
Try this out:
$output = '';
if(mysqli_num_rows($result) == 0){
// echo error;
} else {
while($row = mysqli_fetch_assoc($result)){
$project_no = $row['project_no'];
$project_name = $row['project_name'];
$output .= '<option value="' . $project_no . '">' . $project_name . '</option>";
}
}
Then inside of your HTML, print your $output variable inside of your <select> element:
<select>
<?php
print("$output");
?>
</select>
It should print all options for every row that you have requested from the database.
Hope this helps :)
Try this:
$result = mysqli_query($con,"SELECT * FROM project");
if( mysqli_num_rows( $result )==0){
echo "<tr><td>No Rows Returned</td></tr>";
}else{
echo "<select name=Pname >";
while ($row = mysqli_fetch_assoc($result)) {
echo "<option value="$row["project_no"]">"$row["project_name"]"</option>";
}
echo "</select>";
}
This is the result code that i can run it. I put this code in a form code of html
$result = mysqli_query($con,"SELECT * FROM project"); ?>
<?php
$output = '';
if(mysqli_num_rows($result) == 0){
// echo error;
} else {
echo " <select name = Pname>";
while($row = mysqli_fetch_assoc($result)){
$project_no = $row['project_no'];
$project_name = $row['project_name'];
$output = "<option value=" . $project_no . "> ". $project_name ." </option>";
print("$output");
}
echo " </select>";
}
?>
Thank you every one for helping me ^^
I have a project in php. When I bind select dropdown list with selected value as well as all others values inside the database the one value which is as selected will bind two times, one as first selected value and other as list values.
Below is my code.
$query1 = mysql_query("select * from pincode_master where pcode_id='1'");
while ($row1 = mysql_fetch_array($query1))
{
$city_id = $row1['city_id'];
$sql1="SELECT city_name from city_master where city_id='$city_id'";
$result1=mysql_query($sql1);
$row = mysql_fetch_row($result1);
#$city_name = $row[0];
$query11 = "select * from city_master";
$result11 = mysql_query($query11);
echo "<select name = 'cityname'>";
while (($row11 = mysql_fetch_row($result11)) != null)
{
echo "<option value = '{$row11['city_name']}'";
if ($city_name == $city_name)
echo "selected = 'selected'";
echo ">{$row11['city_name']}</option>";
}
echo "</select>";
}
You should write your query outside loop.
Write your code as below:-
// Check query error
$query1 = mysql_query( "select * from pincode_master where pcode_id='1'" ) or die( mysql_error());
// Check query error
$result11 = mysql_query( "select * from city_master" ) or die( mysql_error());
while ( $row1 = mysql_fetch_assoc( $query1 ) ) {
$city_id = $row1['city_id'];
echo "<select name = 'cityname'>";
while ($row11 = mysql_fetch_assoc( $result11 )) {
$selected = $row11['city_id'] == $city_id ? "selected = 'selected'" : '';
echo "<option value = '{$row11['city_name']}' $selected >". $row11['city_name'] ."</option>";
}
echo "</select>";
}
Hope it will help you :)
Please check this -
is that what you want ?
<select name="yourselection">
<option value="">--Select--</option>
<?php
$msql = mysql_query("SELECT * FROM tablename");
while($m_row = mysql_fetch_array($msql))
echo("<option value = '" . $m_row['table_column1'] . "'>" . $m_row['table_column2'] . "</option>");
?>
</select>
you will get more info here
$i = 1;
$tbl = "";
$field = "";
if($_POST['jenis']=="Bahan Baku")
{
$tbl = "bahanbaku";
$field = "bb_";
}
else if($_POST['jenis']=="Bahan Penunjang")
{
$tbl = "bahanpenunjang";
$field = "bp_";
}
<select class="span10" name="jenis" class="add-on">
<?php
$opt = "SELECT bb_nama FROM ".$tbl."";
$result = mysql_query($opt);
if($row = mysql_fetch_array($result))
{
echo "<option>". $row[$field.'nama'] ."</option>";
}
?>
</select>
The result is none of the selected rows displayed. which line is wrong?
while ($row = mysql_fetch_array($result))
{
echo "<option>". $row[$field.'nama'] ."</option>";
}
Change
if($row = mysql_fetch_array($result))
for
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
in order to iterate over the entire resultset
$opt = "SELECT bb_nama FROM ".$tbl."";
you are selecting the field bb_nama, but when you retrieving time you are doing $row[$field.'nama']. the field is mismatch while the table value is changing.
in other case, query should be
$opt = "SELECT ".$field."_nama FROM ".$tbl."";
I have 3 drop downs I want to display whatever the user will select after he/she has selected a function or a scrpt will do but it must be within the script
<?php
$resource_names = mysql_query("SELECT DISTINCT NAME FROM selections ORDER BY id ASC");
$names = array();
while($row = mysql_fetch_row($resource_names)){
$names[] = $row[0]
}
$resource_surnames = mysql_query("SELECT DISTINCT SURNAME FROM selections ORDER BY id ASC");
$surnames = array();
while($row = mysql_fetch_row($resource_surnames)){
$surnames[] = $row[0];
}
$resource_emails = mysql_query("SELECT DISTINCT EMAIL FROM selections ORDER BY id ASC");
$emails = array();
while($row = mysql_fetch_row($resource_emails)){
$emails[] = $row[0];
}
if(count($emails) <= 0 || count($surnames) <= 0 || count($emails) <= 0){
echo 'No results have been found.';
} else {
// Display form
echo '<form name="form" method="post" action="test.php">';
//Names dropdown:
echo '<select name="id" id="names">';
foreach($names as $name) echo "<option id='$name'>$name</option>";
echo '</select>';
//Surnames dropdown
echo '<select name="id" id="surnames">';
foreach($surnames as $surname) echo "<option id='$surname'>$surname</option>";
echo '</select>';
//Emails dropdown
echo '<select name="id" id="emails">';
foreach($emails as $email) echo "<option id='$email'>$email</option>";
echo '</select>';
echo "<button id='write_in_div'>Click me!</button>";
echo '</form>';
}
?>
Something that will call the write_in_div When Click me! button is press or any other method that can be used to display 3 selection user selected
The Output should be something like You select 1) Name 2)Surname and Email
You have an error in your html selects each select has the same name "id" they each need to be unique so you can detect then.
You need to detect if the user has submitted the form
if(isset($_POST["select_name"])) {
echo $_POST["select_name"];
}
There is a big mistake on you form.
In a form, each select and input MUST have a unique name. You need this name to retrieve the submitted value back in your php script.
I suppose you have this:
<?php
$resource_names = mysql_query("SELECT DISTINCT NAME FROM selections ORDER BY id ASC");
$names = array();
while($row = mysql_fetch_row($resource_names)){
$names[] = $row[0]
}
$resource_surnames = mysql_query("SELECT DISTINCT SURNAME FROM selections ORDER BY id ASC");
$surnames = array();
while($row = mysql_fetch_row($resource_surnames)){
$surnames[] = $row[0];
}
$resource_emails = mysql_query("SELECT DISTINCT EMAIL FROM selections ORDER BY id ASC");
$emails = array();
while($row = mysql_fetch_row($resource_emails)){
$emails[] = $row[0];
}
if(count($emails) <= 0 || count($surnames) <= 0 || count($emails) <= 0){
echo 'No results have been found.';
} else {
// Display form
echo '<form method="post" action="test.php">';
//Names dropdown:
echo '<select name="names">';
foreach($names as $name) echo "<option id='$name'>$name</option>";
echo '</select>';
//Surnames dropdown
echo '<select name="surnames">';
foreach($surnames as $surname) echo "<option id='$surname'>$surname</option>";
echo '</select>';
//Emails dropdown
echo '<select name="emails">';
foreach($emails as $email) echo "<option id='$email'>$email</option>";
echo '</select>';
echo '<button id="write_in_div">Click me!</button>';
echo '</form>';
}
When the form is submitted, test.php will have the posted data: $_REQUEST['names'], $_REQUEST['surnames'] and $_REQUEST['emails'].
You just have to check the content of thoses vars and print them if not null.
Note1: ?> is useless at the end of a file.
Note2: be carefull about ' and " when writing an html file. The value of an html attribute is written with ", not '.
I am trying to populate a Drop down box from results of a mySQL Query, in Php. I've looked up examples online and I've tried them on my webpage, but for some reason they just don't populate my drop down box at all. I've tried to debug the code, but on the websites I looked at it wasn't really explained, and I couldn't figure out what each line of code. Any help would be great :)
Here's my Query: Select PcID from PC;
You will need to make sure that if you're using a test environment like WAMP set your username as root.
Here is an example which connects to a MySQL database, issues your query, and outputs <option> tags for a <select> box from each row in the table.
<?php
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');
$sql = "SELECT PcID FROM PC";
$result = mysql_query($sql);
echo "<select name='PcID'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['PcID'] . "'>" . $row['PcID'] . "</option>";
}
echo "</select>";
?>
Below is the code for drop down using MySql and PHP:
<?
$sql="Select PcID from PC"
$q=mysql_query($sql)
echo "<select name=\"pcid\">";
echo "<option size =30 ></option>";
while($row = mysql_fetch_array($q))
{
echo "<option value='".$row['PcID']."'>".$row['PcID']."</option>";
}
echo "</select>";
?>
Since mysql_connect has been deprecated, connect and query instead with mysqli:
$mysqli = new mysqli("hostname","username","password","database_name");
$sqlSelect="SELECT your_fieldname FROM your_table";
$result = $mysqli -> query ($sqlSelect);
And then, if you have more than one option list with the same values on the same page, put the values in an array:
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
And then you can loop the array multiple times on the same page:
foreach ($rows as $row) {
print "<option value='" . $row['your_fieldname'] . "'>" . $row['your_fieldname'] . "</option>";
}
No need to do this:
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
You can directly do this:
while ($row = mysqli_fetch_array($result)) {
echo "<option value='" . $row['value'] . "'>" . $row['value'] . "</option>";
}
At the top first set up database connection as follow:
<?php
$mysqli = new mysqli("localhost", "username", "password", "database") or die($this->mysqli->error);
$query= $mysqli->query("SELECT PcID from PC");
?>
Then include the following code in HTML inside form
<select name="selected_pcid" id='selected_pcid'>
<?php
while ($rows = $query->fetch_array(MYSQLI_ASSOC)) {
$value= $rows['id'];
?>
<option value="<?= $value?>"><?= $value?></option>
<?php } ?>
</select>
However, if you are using materialize css or any other out of the box css, make sure that select field is not hidden or disabled.
After a while of research and disappointments....I was able to make this up
<?php $conn = new mysqli('hostname', 'username', 'password','dbname') or die ('Cannot connect to db') $result = $conn->query("select * from table");?>
//insert the below code in the body
<table id="myTable"> <tr class="header"> <th style="width:20%;">Name</th>
<th style="width:20%;">Email</th>
<th style="width:10%;">City/ Region</th>
<th style="width:30%;">Details</th>
</tr>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row['username']."</td>";
echo "<td>".$row['city']."</td>";
echo "<td>".$row['details']."</td>";
echo "</tr>";
}
?>
</table>
Trust me it works :)
What if you want to use both id and name in the dropdown? Here is the code for that:
$mysqli = new mysqli($servername, $username, $password, $dbname);
$sqlSelect = "SELECT BrandID, BrandName FROM BrandMaster";
$result = $mysqli -> query ($sqlSelect);
echo "<select id='brandId' name='brandName'>";
while ($row = mysqli_fetch_array($result)) {
unset($id, $name);
$id = $row['BrandID'];
$name = $row['BrandName'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";