I'm trying to get a drop down menu to keep its selected value when the user hits submit, but it fails due to errors on the form.
I have a while loop returning values from a database to build the options for the drop down, but how do I echo "selected" on the right option?
I have tried if($district == $row["name"]) { echo "selected";} as you see below, but it doesn't work.
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
while ($row = mysql_fetch_array($result)) {
echo '<option value="{$row["name"]}"'; if($district == $row["name"]) { echo "selected";} ; echo '>' . $row["name"] . "</option>";
}
?>
Sorry for the delay. None of the suggested answers worked for me. Any other ideas?
Can you try this,
<?php
$result = mysql_query("SELECT dist.name FROM districts AS dist JOIN int_bd AS ibd ON dist.id = ibd.districts_id WHERE banners_id = 6 GROUP BY dist.id ORDER BY dist.id ASC", $connection);
if (!result) {
die("Database query failed: " . mysql_error());
}
$district = $_REQUEST['name']; // You need pass the value you have been submitted
while ($row = mysql_fetch_array($result)) {
$selected ="";
if(trim($district) == trim($row["name"])) { $selected = "selected";}
echo '<option value="{$row["name"]}" '.$selected.' >' . $row["name"] . "</option>";
}
?>
Try this..
if($district == $row["name"])
{
echo "<option value='$district' selected>$district</option>";
}
I just found the answer. This is what I did:
while ($row = mysql_fetch_array($result)) {
echo '<option value="' . $row["name"] . '"';
if($row["name"] == $district) { echo 'selected';} ;
echo '>' . $row["name"] . '</option>';
}
It seems to have been this line
echo '<option value="{$row["name"]}"';
that was causing the problem.
Related
I am using the below code to populate drop down list in php html,
<?php
$mid="mario";
$sql = "SELECT * FROM tbl_prdy WHERE col_master_id = '$mid'";
$result = mysqli_query($conn,$sql);
echo "<select name='list'>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col_of_fa'] . "'>" . $row['col_of_fa'] . "
</option>";
}
echo "</select>";
?>
But, I am getting internal server error. I have debugged the code and found that the issue is with the following 2 lines in the above code. There is not much information in server logs. Can you tell me what might be the issue with the following 2 lines of code?
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['col_of_fa'] . "'>" . $row['col_of_fa'] .
"/option>";
}
mixing mysqli with mysql
change
$row = mysql_fetch_array($result)
to
$row = mysqli_fetch_array($result)
You would use this
while($row=mysqli_fetch_assoc($result )){
}
or
while($row=mysqli_fetch_array($result )){
}
//Try this :
while ($row = mysqli_fetch_array($result)) { ?>
<option value="<?php echo $row['col_of_fa'] ?>" ><?php echo $row['col_of_fa'] ?>
</option>
<?php }
So I've spent a bit of time looking at MySQLi and I'm having trouble updating a script with the new functions. This script is used for a dynamic dropdown form, using data sent to it using JS. You can find a live version of the script here to check out what I'm takling about. I've looked up and down my code and have compared it to other MySQLi examples and I'm just not sure where I'm going wrong.
Now, the first dropdown doesn't even initiate a query, all the PHP does is return predefined results as it's just simpler for the first option. What's weird, to me, is that even the first drop down is now not working when it does not rely at all on the MySQLi connection. It all worked before updating, just for reference.
Here's my script:
$db = new mysqli($dbHost, $dbUser, $dbPass, $dbDatabase);
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
//prevents injections
//any order
isset($_GET['type'])?$type = urldecode($_GET['type']):"";
isset($_GET['source'])?$source = $db->real_escape_string(urldecode($_GET['source'])):"";
isset($_GET['range'])?$power = $db->real_escape_string(urldecode($_GET['range'])):"";
isset($_GET['setpoint'])?$setpoint = $db->real_escape_string(urldecode($_GET['setpoint'])):"";
//forms the query depending on what data is recieved through GET
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' AND stp='$setpoint' ORDER BY model";
} elseif (isset($_GET['power'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' ORDER BY model";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT pso FROM meters WHERE sio='$range' ORDER BY model";
} elseif (isset($_GET['source'])) {
$query = "SELECT DISTINCT sir FROM meters WHERE sio LIKE '%$source%' ORDER BY sir";
}
//creates a result array from query results
isset($query)?$result = $db->query($query):"";
//outputs dropdown options dependent on what GET variables are set
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['stp'] . "'>" . $row['stp'] . "</option>";
$result->free();
}
} elseif (isset($_GET['power'])) {
echo "<option>Please Choose Setpoint Options</option>";
while ($row = $result->fetch_assoc()) {
$row{'stp'} = ucfirst($row{'stp'}); //capitalizes the first letter; necessary?
echo "<option value='" . $row['stp'] . "'>" . $row['stp'] . "</option>";
$result->free();
}
} elseif (isset($_GET['source'])) {
echo "<option>Please Choose Input Range</option>";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['sir'] . "'>" . $row['sir'] . "</option>";
$result->free();
}
} elseif (isset($_GET['type']) && $_GET['type'] == "Digital") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='RS232C'>RS232C</option><option value='RS422'>RS422</option><option value='RS485'>RS485</option><option value='current loop'>current loop</option>";
$result->free();
} elseif (isset($_GET['type']) && $_GET['type'] == "Analog") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='DC current'>DC Current</option><option value='DC voltage'>DC Voltage</option><option value='AC current'>AC Current</option><option value='AC voltage'>AC Voltage</option><option value='process'>Process</option><option value='thermocouple'>Thermocouple</option><option value='RDT'>rdt</option>";
$result->free();
}
edit: This is my old code using the deprecated method.
$con = mysql_connect($dbHost, $dbUser, $dbPass) or trigger_error("Failed to connect to MySQL Server. Error: " . mysql_error());
mysql_select_db($dbDatabase) or trigger_error("Failed to connect to database {$dbDatabase}. Error: " . mysql_error());
//prevents injections
//any order
isset($_GET['type'])?$type = urldecode($_GET['type']):"";
//$type = mysql_real_escape_string(urldecode($_GET['type']));
isset($_GET['source'])?$source = mysql_real_escape_string(urldecode($_GET['source'])):"";
isset($_GET['range'])?$power = mysql_real_escape_string(urldecode($_GET['range'])):"";
isset($_GET['setpoint'])?$setpoint = mysql_real_escape_string(urldecode($_GET['setpoint'])):"";
//forms the query depending on what data is recieved through GET
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' AND stp='$setpoint' ORDER BY model";
} elseif (isset($_GET['power'])) {
$query = "SELECT DISTINCT stp FROM meters WHERE sio='$range' AND pso='$power' ORDER BY model";
} elseif (isset($_GET['range'])) {
$query = "SELECT DISTINCT pso FROM meters WHERE sio='$range' ORDER BY model";
} elseif (isset($_GET['source'])) {
$query = "SELECT DISTINCT sir FROM meters WHERE sio LIKE '%$source%' ORDER BY sir";
}
//creates a result array from query results
isset($query)?$result = mysql_query($query):"";
//outputs dropdown options dependent on what GET variables are set
//first option on the bottom; last option on the top to avoid conflicts
if (isset($_GET['setpoint'])) {
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['power'])) {
echo "<option>Please Choose Setpoint Options</option>";
while ($row = mysql_fetch_array($result)) {
$row{'stp'} = ucfirst($row{'stp'}); //capitalizes the first letter; necessary?
echo "<option value='" . $row{'stp'} . "'>" . $row{'stp'} . "</option>";
}
} elseif (isset($_GET['source'])) {
echo "<option>Please Choose Input Range</option>";
while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row{'sir'} . "'>" . $row{'sir'} . "</option>";
}
} elseif (isset($_GET['type']) && $_GET['type'] == "Digital") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='RS232C'>RS232C</option><option value='RS422'>RS422</option><option value='RS485'>RS485</option><option value='current loop'>current loop</option>";
} elseif (isset($_GET['type']) && $_GET['type'] == "Analog") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='DC current'>DC Current</option><option value='DC voltage'>DC Voltage</option><option value='AC current'>AC Current</option><option value='AC voltage'>AC Voltage</option><option value='process'>Process</option><option value='thermocouple'>Thermocouple</option><option value='RDT'>rdt</option>";
}
You are freeing your $result inside the while loop. This will cause the loop to fail on the second iteration.
Since you are freeing the result in all of the ifs, why don't you just do it once at the end?
...
} elseif (isset($_GET['type']) && $_GET['type'] == "Analog") {
echo "<option>Please Choose Input Source</option>";
echo "<option value='DC current'>DC Current</option><option value='DC voltage'>DC Voltage</option><option value='AC current'>AC Current</option><option value='AC voltage'>AC Voltage</option><option value='process'>Process</option><option value='thermocouple'>Thermocouple</option><option value='RDT'>rdt</option>";
}
$result->free();
However this doesn't explain why analog and digital won't work still..
I have trying to print the selected value in the drop down list, but in vain. I am new to php and html, so this might sound like a stupid question but please help me out! this is my code:
echo '<tr><td>Client:</td><td><select name="client_name">';
$sql = mysql_query("SELECT * FROM client");
$s= mysql_query("SELECT project.client_id, client_name, client.client_id FROM client,project where project.client_id=client.client_id AND project_id='$editId'");
// $s2= mysql_fetch_array($s);
while ($row = mysql_fetch_array($sql))
{
while ($s2==mysql_fetch_array($s))
{
if ($row['client_id'] == $s2['client_id'])
$selected = "selected=\"selected\"";
else
$selected = " ";
}
echo '<option value="' . $row['client_id'] . '" ' . ($selected == $row['client_id'] ? ' selected' : '') . '>' . $s2['client_name'] . '</option>';
}
This code doesnt work. Please help me out! Is there a different way to do it?
Try this
echo '<tr><td>Client:</td><td><select name="client_name">';
$sql = mysql_query("SELECT * FROM client");
$s= mysql_query("SELECT project.client_id, client_name, client.client_id FROM client,project where project.client_id=client.client_id AND project_id='$editId'");
// $s2= mysql_fetch_array($s);
while ($row = mysql_fetch_array($sql))
{
while ($s2==mysql_fetch_array($s))
{
if ($row['client_id'] == $s2['client_id'])
$selected = "selected=\"selected\"";
else
$selected = " ";
}
echo '<option value="' . $row['client_id'] . '" ' . $selected . '>' . $s2['client_name'] . '</option>';
}`
This query is a problem
$s= mysql_query("SELECT project.client_id, client_name, client.client_id FROM client,project where project.client_id=client.client_id AND project_id='$editId'");
you are trying to get two client ids project.client_id and client.client_id, in such cases you should give aliases like project.client_id as project_client_id and client.client_id as client_client_id, then use that value to compare in while loop.
Note use whichever client id you want either project_client_id or client_client_id.
I can't see the result in the select area
<?php
require 'config.php';
$query = "SELECT cat_id, category FROM categories LIMIT 1";
$result = mysqli_query($con,$query);
if(!$result){
echo 'Query failed : '.mysqli_error();
exit(0);
}
while($row = mysqli_fetch_assoc($result)) {
echo '<select name="cat_id">
' . $row['cat_id'] . '
</select>';
}
mysqli_close($con);
?>
I try to add the HTML select tag but it still isn't working.
This is not a good format for select
echo '<select name="cat_id">
' . $row['cat_id'] . '
</select>';
It should be
echo '<select name="cat_id">';
while($row = mysqli_fetch_assoc($result)) {
echo '<option value="'.$row['cat_id'] .'">'.$row['cat_id'].'</option>';
}
echo '</select>';
i have be been trying to put a count query into a drop down as i am creating a rating type system and based on the number of rows in a database i want to return a scale for example 1-5
<?php
// Ruth Gammack
session_start();
$page = 'index.php';
mysql_connect('localhost', 'root', '') or die(mysql_error());
mysql_select_db('group4') or die(mysql_error());
//echo "Done";
require_once "./includes/choices.inc.php";
if(isset($_GET["action"])){
switch($_GET["action"]) {
case "add":
addmodule();
break;
case "remove":
removemodule();
break;
case "empty":
emptychoice();
break;
}
reviewChoices();
// close database connection
dbClose($conn);
}
function modules(){
$get = mysql_query('SELECT * FROM module');
if (mysql_num_rows($get) == 0){
echo '<p>There are no Modules available at this time please check back later</p>';
}
else {
while ($get_row = mysql_fetch_assoc($get)) {
echo '<p>'.$get_row['moduleID'].'<br />'.$get_row['ModuleName'].'<br />'.$get_row['ModuleDesc'].'<br />'.$get_row['LecturerID'].'</p>';
// printing the list box select command
$query_disp=('SELECT moduleID, COUNT(*) FROM module');
$result_disp = mysql_query($query_disp);
echo "<select name=”selRating”>";
while($row = mysql_fetch_array($result_disp))
{
echo "<option value='" . $row['moduleID'] . "'>" . $row['moduleID'] . "</option>";
/* Option values are added by looping through the array */
}
echo "</select>";// Closing of list box
}
}
}
?>
i have tried many different ways but I have run out of ideas.
Maybe something like this (not tested)?
$query_disp=('SELECT moduleID, ModuleName, ModuleDesc, LecturerID, COUNT(*) AS cnt FROM module GROUP BY moduleID');
$select = "<select name=”selRating”>";
while($row = mysql_fetch_array($query_disp))
{
echo '<p>'.$get_row['moduleID'].'<br />'.$get_row['ModuleName'].'<br />'.$get_row['ModuleDesc'].'<br />'.$get_row['LecturerID'].'</p>';
$select += "<option value='" . $row['moduleID'] . "'>" . $row['ModuleName'] . " " . $row['cnt'] . "</option>";
}
$select += '</select>';
echo $select;