Amir Bhandari Amir Bhandari - 17 days ago 5
PHP Question

Select ID from database when user selects value in drop down

I have a table which contains

ID
and
DOC_DESC
. When user selects the
DOC_DESC
from the drop down and submits,
ID
of that particular row should be printed.

I have written following code:

<?php
mysql_connect("localhost","root","");
mysql_select_db("dbtest");
?>
<form name="form1" method="post" action="">
<?
$sql=mysql_query("SELECT ID,DOC_DESC FROM document_type_master");
if(mysql_num_rows($sql)){
$select= '<select name="select">';
while($rs=mysql_fetch_array($sql)){
$select.='<option value="'.$rs['ID'].'">'.$rs['DOC_DESC'].'</option>';
}
}
$select.='</select>';
echo $select;
?>
<input type="submit" value="Submit" name="submit">
</form>

<?php
if(!isset($_POST['submit']))
{
echo " "; //ID should be printed here
}
?>


I am also getting error as:
mysql_num_rows() expects parameter 1 to be resource, boolean given

Answer

You didn't pass the connection instance to mysql_query(). So the result resource is not available for the mysql_num_rows() function.

$link = mysql_connect("localhost","root","");
mysql_select_db("dbtest",$link);
?>
<form name="form1" method="post" action="">
<?
$sql=mysql_query("SELECT ID,DOC_DESC FROM document_type_master",$link);
  if(mysql_num_rows($sql)){
    $select= '<select name="select">';
    while($rs=mysql_fetch_array($sql)){
       $select.='<option value="'.$rs['ID'].'">'.$rs['DOC_DESC'].'</option>';
  }
}
$select.='</select>';
echo $select;
?>
<input type="submit" value="Submit" name="submit">
</form>
Comments