Jump to content

[SOLVED] Simple question with listbox default value


patheticsam

Recommended Posts

Yep, it is.

 

EDIT:

A better question would be, "I have tried to get this listbox to set a default value from a DB but I cannot figure out how. Here is my current code, could someone help me out?"

 

You probably would have got a solution from me then.

Can you do this *insert thing*

Ok here's the code I have now :

 

 

 

<?php

 

$db = mysql_connect('localhost', 'username', 'password');

 

mysql_select_db('database',$db);

 

$sql = "SELECT field1, field2, field3 FROM table1 WHERE id='$id'";

 

$req = mysql_query($sql) or die('Erreur SQL <br>'.$sql.'<br>'.mysql_error());

 

while($data= mysql_fetch_assoc($req))

      {

 

Basicly if field1 = option2 in mySQL. Then the default selected value should be Option 2

 

echo "

      <select name=select selected="$data[field1]">

      <option value=option1>Option 1</option>

      <option value=option2>Option 2</option>

      <option value=option3>Option 3</option>

      <option value=option4>Option 4</option>

      <option value=option5>Option 5</option>

      </select>

      ";

      }

?>

 

How can I do that? Thanks for your help!!!

 

 

You need to put SELECTED in the options tag, not the select tag.

<?php
echo "
       <select name=select>
       <option value=option1 SELECTED>Option 1</option>
       <option value=option2>Option 2</option>
       <option value=option3>Option 3</option>
       <option value=option4>Option 4</option>
       <option value=option5>Option 5</option>
       </select>
       ";
       }
?>

 

I would do this:

<?php
// Create an array of all of the possible values
$selectArray = array(
'option1' => 'Option 1',
'option2' => 'Option 2',
'option3' => 'Option 3',
'option4' => 'Option 4',
'option5' => 'Option 5',
)

// Start the option list.
echo '<select name="select">';

// loop through the array
foreach($selectArray as $value => $title) {

// Create an option
echo '<option value="',$value,'"';

// Check to see if the value is the one that was found in tthe database
if($value==$data['field1']) 
	echo ' SELECTED';

// Finish creating the option
echo '>',$title,'</option>';
}

// Close out the option list
echo '</select>';
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.