在where子句中有未知列'chenzhen'

时间:2013-10-19 19:08:10

标签: php mysql mysqli

我有一个PHP脚本,使用mysqli扩展连接MySQL数据库,根据用户名或ID搜索Blog帖子。我创建了一个名为BlogSearch的VIEW,它使用其他表中的连接来聚合我需要的信息,如下所示:

它从中提取的表名为Profiles,其中包含用户信息,BlogPostsBlogCategory

我每次搜索时都会收到错误消息: Unknown column 'chenzhen' in 'where clause'

我在下面使用的PHP代码:

require 'database.php'; 

        $query = "SELECT * FROM BlogSearch";

  echo <<<EOF
<form method='post' action='' style="padding: 30px 0;">
        <table cellspacing="0" border="0" style="float: left;">
        <tr>
        <td>Search Blog Posts by Username/ID</td>
        <td><input type="text" id="search" name="search" style="width: 300px;"/></td>
        <td><input type="submit" id="submit_button" value="Search" name="submit_button" style="float: right;" /></td>
        </tr>
        </table>
    </form>
EOF;

        if(isset($_POST['submit_button'])) 
    {
        $search_term = $_POST['search'];
          $query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";


        // run the query and store the results in the $result variable.
        $result = $mysqli->query($query) or die(mysqli_error($mysqli));

    }

    if ($result) {

  // create a new form and then put the results
  // into a table.



  echo "<form method='post' action='delete.php' style='clear: both;'>"; 
  echo "<table cellspacing='0' cellpadding='15'>
        <th width='5%'>
        <input type='checkbox' id='allcb' onclick='checkAll(this)' name='allcb' />Check All
        </th>
        <th width='10%'>User</th>
        <th width='85%'>Blog Post Title</th>
        ";


  while ($row = $result->fetch_object()) {

        $title = substr($row->PostCaption,0,50);
        $id = $row->PostID;
        $user = $row->NickName;

        //put each record into a new table row with a checkbox
    echo "<tr>
            <td><input type='checkbox' name='checkbox[]' id='checkbox[]'  value=$id />
            <td>$user</td>
            <td>$title</td>
         </tr>"; 

    }

    // when the loop is complete, close off the list.
    echo "</table><p><input id='delete' type='submit' class='button' name='delete' value='Delete Selected Items'/></p></form>";
}

我不知道为什么它甚至将用户名识别为列。任何人都可以指出我正确的方向来解决这个问题吗?

提前致谢。

2 个答案:

答案 0 :(得分:1)

SQL查询中不是SQL关键字或文字(用单引号表示)的任何元素都被假定为对象(例如表,列)名称。

您的问题是$search_term子句中WHERE周围缺少引号:

$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = $search_term ";

你应该添加它们,因为:

$query = $query . " WHERE `NickName` LIKE '%$search_term%' OR ID = '$search_term' ";

答案 1 :(得分:1)

$ search_term 包含在where '$search_term'

之类的子句中的单引号中