2013-10-19 96 views
-1

中的未知列'chenzhen'我有一個PHP腳本,它使用mysqli擴展連接到MySQL數據庫,以根據用戶名或ID搜索博客帖子。我創建了一個名爲BlogSearch查看使用聯接形成其他表彙總是這樣表示我需要共同的信息:在條款

它被稱爲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>"; 
} 

我不知道爲什麼它甚至將用戶名確定爲列。任何人都可以指出我正確的方向來解決這個問題嗎?

在此先感謝。

回答

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' "; 
+0

某事很簡單,但我錯過了。即使我嘗試了許多不同的變體,即使使用這種方法,它直到現在才起作用。非常感謝它的作品! – Tower

+0

注意qoute或不要這樣做的問題......如果表列類型是一個字符串類型,如果您的列類型是一個int類型,總是使用像'1'qoute qoute .. MySQL正在使用轉換器來轉換數據類型什麼會造成額外的開銷或在某些情況下可能導致無用的索引 –

1

附上您的$ SEARCH_TERM在在單引號像這樣的條款'$search_term'