Jump to content

assign a default value in a field with a sql select query with php


JayDude

Recommended Posts

I created a drop-down menu using a MySQL statement in php for a form.

My drop down menu works fine, but I want to assign a default value to it (normal text) the value will never change,

thus I do not need to extract the default value from the table, I already know the value.

 

Here is the basic snippet from the script:

 

<?php

include("../includes/xxx.php");

$cxn = mysqli_connect($host,$user,$password,$dbname);

$query = "SELECT DISTINCT `plant_id` FROM `plant` ORDER BY `plant_id`";

$result = mysqli_query($cxn,$query);

while($row = mysqli_fetch_assoc($result))

{

extract($row);

echo "<option value='$plant_id'>$plant_id</option>\n";

}

?>

Link to comment
Share on other sites

<?php
include("../includes/xxx.php");
$cxn = mysqli_connect($host,$user,$password,$dbname);
$query = "SELECT DISTINCT `plant_id` FROM `plant` ORDER BY `plant_id`";
$result = mysqli_query($cxn,$query);
while($row = mysqli_fetch_assoc($result))
{
extract($row);
$selected = ($plant_id == EXPECTED_ID ? "selected='selected'" : "");
echo "<option value='$plant_id' {$selected}>$plant_id</option>\n";
}
?>

 

Obviously replace the EXPECTED_ID with whatever your selected plant ID should be.

Link to comment
Share on other sites

I tried that, but now my dropdown list gives an empty field with a blank dropdown list.

 

Here is the snippet you gave me with the altered field:-

(note I used ' ' else I get an error)

 

{

extract($row);

$selected = ($plant_id == 'Blue' ? "selected='selected'" : "");

echo "<option value='$plant_id' {$selected}>$plant_id</option>\n";

}

Link to comment
Share on other sites

CPD,

 

Ignore my last post, it is working fine, thanks for the help...

 

But I now have another question for you, maybe a bit more challenging.

 

I have another dropdown list in the same form, script looks exactly like my first (and working fine)

but this dropdown menu must only show items from the table corresponding with the first selected field.

I have seen this in carsales websites so I know it can be done.

 

Please help

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.