使用php和mysql不存在获取表

时间:2015-09-26 20:24:06

标签: php mysql

这里的代码应该搜索数据库。但我得到的错误是我的桌子不存在。而且我想问为什么如果我按下第二次提交按钮它只是跳到else所以它回显choose at least.... and also all data from database.谢谢!

这是php

    if (isset($_POST['submit'])) {                                                   
   $query = 'SELECT * FROM station_tab';
   if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone'])) 
   {
      $query .= 'WHERE station_name' .mysql_real_escape_string($_POST['station_name']) . 'AND city' . mysql_real_escape_string($_POST['city']) . 'AND zone' . mysql_real_escape_string($_POST['zone']);   
   } elseif (!empty($_POST['station_name'])) {
      $query .= 'WHERE station_name' . mysql_real_escape_string($_POST['station_name']);
   } elseif (!empty($_POST['city'])) {
      $query .= 'WHERE city' . mysql_real_escape_string($_POST['city']);
   } elseif (!empty($_POST['zone'])) {
      $query .= 'WHERE zone' . mysql_real_escape_string($_POST['zone']);
   } else {
   echo "Choose at least one option for search";
   }
    $result = mysql_query($query, $db) or die(mysql_error($db));    
    if (mysql_num_rows($result) > 0) {
    while ($row = mysql_fetch_array($result)){    
    echo '<br/><em>' .$row['station_name'] . '</em>';
    echo '<br/>city: '. $row['city'];  
    echo '<br/> zone: ' .$row['zone'];
    echo '<br/> Long: ' .$row['lon'];
    echo '<br/> Lat: ' . $row['lat'];  
    }    
  }
  } 

当我向城市添加城市名称时,这是错误消息。

Table 'stanice_tab.station_tabwhere' doesn't exist

2 个答案:

答案 0 :(得分:1)

以下是您更正后的代码:

   $query = 'SELECT * FROM station_tab '; // note the space at the end
   if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone'])) {
      $query .= ' WHERE station_name = "' .mysql_real_escape_string($_POST['station_name']) . '" AND city = "' . mysql_real_escape_string($_POST['city']) . '" AND zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = signs and the space before each AND 
   } elseif (!empty($_POST['station_name'])) {
      $query .= ' WHERE station_name = "' . mysql_real_escape_string($_POST['station_name']).'"'; // note the = sign and the space at the beginning
   } elseif (!empty($_POST['city'])) {
      $query .= ' WHERE city = "' . mysql_real_escape_string($_POST['city']).'"'; // note the = sign and the space at the beginning
   } elseif (!empty($_POST['zone'])) {
      $query .= ' WHERE zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = sign and the space at the beginning
   } else {
       echo "Choose at least one option for search";
   }

养成echo $query变量的习惯,这样连接不会增加任何拼写错误。

答案 1 :(得分:0)

在phpmyadmin中

选择数据库,然后选择你的表

在上面的菜单中有一个sql菜单。您可以使用此功能构建SQL查询或在出现此类错误时进行调试