Reputation: 21
I want to add a dynamic select list, which contain my data from php. how should i do it? i also wanted to have arguments with variables from other php file e.g $mentor==$rows. appreciate it
<th><select name="mentor" style="width:95%">
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db("testproject", $conn);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT mtrname FROM mentors";
$sql2 = "SHOW COLUMNS from mentors";
$result= mysql_query( $sql, $conn );
if(! $result)
{
die('Could not get data: ' . mysql_error());
}
$fetchrow = mysql_fetch_row($sql2);
$num = count($fetchrow);
while($rows = mysql_fetch_array($result))
{
for($i=0;$i<$num;$i++)
{
$rows[$i];
}
}
mysql_close($conn);
?>
<option value="<?php echo $mentor?>" <?php if($mentor==$rows[i]) echo 'selected'?>><?php echo $mentor?></option>
</select></th>
edited:
so i am trying to put select option into when the user first include the data. what i've tried is
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db("testproject", $conn);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
$sql = "SELECT mtrname FROM mentors";
$sql2 = "SHOW COLUMNS from mentors";
$result= mysql_query( $sql, $conn );
if(! $result)
{
die('Could not get data: ' . mysql_error());
}
$fetchrow = mysql_fetch_row($sql2);
$num = count($fetchrow);
while($rows = mysql_fetch_array($result))
{
for($i=0;$i<$num;$i++)
{
echo"<option value='".$rows[i].">".$rows[i]."</option>";
}
}
mysql_close($conn);
?>
but it doesnt display anything from the mentor table. is my code incorrect or its my mysql database issue?
Upvotes: 1
Views: 3756
Reputation: 2096
You should move from mysql since it's not deperecated and move towards PDO or mysqli. If the results being returned are correct then you're pretty much there. Just move the option
tag inside the for()
loop.
while($rows = mysql_fetch_array($result))
{
for($i=0;$i<$num;$i++)
{
echo "<option value='$mentor'". ($mentor==$rows[i] ? 'selected' : '') .">$mentor</option>";
}
}
Upvotes: 1