Forum Moderators: coopster

Message Too Old, No Replies

Need help for scripting php

         

Ashish1189

2:40 pm on Jul 29, 2010 (gmt 0)

10+ Year Member



Hello all,
I am a php beginner please help me out.
I have a database named "state" in MySQL.
In it m having a table "cities" with columns "id" and "Name".
I want to write a php script that will add the contents of column "Name" to the combo box (Combo Box is designed in html).
Please help me as soon as possible.
Thank you.

mooger35

4:33 pm on Jul 29, 2010 (gmt 0)

10+ Year Member



<?php
// connect & select database
$db = mysql_connect('localhost', 'user', 'password');
mysql_select_db('state',$db);

// query db
$query = "SELECT * FROM `cities` ORDER BY `Name` ASC";
$sql = mysql_query($query, $db);
?>
<form action="process.php" method="post">
<select name="cities">
<option>Select a city</option>
<?php
// loop through query results
while($row = mysql_fetch_assoc($sql)){
echo '<option value="'.$row['id'].'">'.$row['Name'].'</option>'."\r\n";
}
?>
</select>
</form>

typed on the fly so there may be an error or two in there.

rocknbil

6:40 pm on Jul 29, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



To add one bit, not needed if it's a search but may be needed if it's an edit form,

echo '<option value="'.$row['id'].'"';
if (isset($_POST['Name']) and ($_POST['Name']==$row['Name'])) { echo ' selected'; } // selected="selected" for XHTML
echo '>'.$row['Name'].'</option>'."\r\n";