php mysql下拉值选择

时间:2016-05-09 09:18:05

标签: php mysql

目前,以下代码显示了各个发布商的过滤器,即如果我选择DC,我将只看到DC标题。

问题是,从当前代码我无法通过下拉菜单显示所有发布商。

<div id="main">
  <form method="post" action="">
    <div id="search_query" >
     <select name="make" size="0">
      <option value="all">All Publishers</option>
      <option value="DC">DC</option>
      <option value="Marvel">Marvel</option>
      <option value="Image">Image</option>
    </select>

    <input type="submit" name="submit" value="submit">

  </div>
</form>
<div id="main_container">
 <?php
 $db_con = mysql_connect('127.0.0.1','root','root');
 if (!$db_con) {
   die('Could not connect: ' . mysql_error());
 }
 mysql_select_db('work', $db_con);
 if(isset($_POST['submit']))
 {
   $make = mysql_real_escape_string($_POST['make']);
   $sql = sprintf("SELECT * FROM products WHERE publisher= '$make' ");

   $result = mysql_query($sql);

   echo "<table width= 970 border=1>
   <tr>
     <th width='120' scope='col'>Title</th>
     <th width='170' scope='col'>Publisher</th>
     <th width='185' scope='col'>Price</th>
     <th width='126' scope='col'>Desc</th>
   </tr>";
   while($row = mysql_fetch_array($result))
   {
     echo "<tr>";
     echo "<td>".$row['title']."</td>";
     echo "<td>". $row['publisher'] . "</td>";
     echo "<td>". $row['price'] ."</td>";
     echo "<td>". $row['desc'] ."</td>";
     echo "</tr>";
   }
   echo "</table>";
 }
 else
 {
  $sql = sprintf("SELECT * FROM products");
  $result = mysql_query($sql);

  echo "<table width= 970 border=1>
  <tr>
   <th width='120' scope='col'>Title</th>
   <th width='170' scope='col'>Publisher</th>
   <th width='185' scope='col'>Price</th>
   <th width='126' scope='col'>Desc</th>
 </tr>";
 while($row = mysql_fetch_array($result))
 {
   echo "<tr>";
   echo "<td>".$row['title']. "</td>";
   echo "<td>". $row['publisher'] . "</td>";
   echo "<td>". $row['price'] ."</td>";
   echo "<td>". $row['desc'] ."</td>";
   echo "</tr>";
 }
 echo "</table>";
} 

mysql_close($db_con);
?>

1 个答案:

答案 0 :(得分:0)

在您的查询中,它正在搜索publisher = $ make,其中$ make =&#34; all&#34;。 您的数据库表可能没有发布者=&#34; make&#34;的任何记录。

我建议您在此处添加if else条件:

if (isset($_POST['submit'])) {

   $make = mysql_real_escape_string($_POST['make']);

   if ($make != "all") {
       $sql = sprintf("SELECT * FROM products WHERE publisher= '$make' ");
   } else {
      $sql = sprintf("SELECT * FROM products");
   }

   /* Other code */
}