2015-11-04 141 views
-4

我有一個SQL搜索嵌入PHP代碼如下「在您的SQL語法錯誤」:PHP/MySQL的搜索功能:

<?php 
include("productconfig.php"); 

$result = mysql_query("SELECT * FROM weeklytbakl") or die(mysql_error()); 

if (isset($_POST['search'])) 
{ 
    $search_term = mysql_real_escape_string($_POST['searchbox']); 

    $sql .= "WHERE description = '{$search_term}'"; 
} 

$query = mysql_query($sql) or die(mysql_error()); 
?> 

<form name="search_form" method="POST" action="displaydata.php"> 
Search: <input type="text" name="searchbox" value="" /> 
<input type="submit" name="search"> 
</form> 
<table width="70%" cellpadding="5" cellspace="5"> 

<tr> 
    <td><strong>ID</strong></td> 
    <td><strong>Code</strong></td> 
    <td><strong>Image Link</strong></td> 
    <td><strong>Description</strong></td> 
    <td><strong>Instock</strong></td> 
    <td><strong>Week 1</strong></td> 
    <td><strong>Week 2</strong></td> 
    <td><strong>Week 3</strong></td> 
    <td><strong>Week 4</strong></td> 
    </tr> 

    <?php while ($row = mysql_fetch_array($query)) 
    { ?> 
    <tr> 
     <td><?php echo $row['id']; ?></td> 
     <td><?php echo $row['code']; ?></td> 
     <td><?php echo $row['image']; ?></td> 
     <td><?php echo $row['description']; ?></td> 
     <td><?php echo $row['instock']; ?></td> 
     <td><?php echo $row['week1']; ?></td> 
     <td><?php echo $row['week2']; ?></td> 
     <td><?php echo $row['week3']; ?></td> 
     <td><?php echo $row['']; ?></td> 
     </tr> 



     <?php }?> 
     </table> 

但代碼給我下面的錯誤:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE description = ''' at line 1

你能幫我找出爲什麼它不能正常工作嗎?

+1

添加一個空格 - '$ SQL =「WHERE' –

+0

要知道,老mysql_ *擴展你使用的是PHP(當前版本)的5.5版本過時,正在您需要遷移到使用mysqli_ *擴展名或PDO – SpacePhoenix

+0

您必須使用like操作符來獲取數據。如果您使用where,它會查找確切的關鍵字。 –

回答

1
<?php 
include("productconfig.php"); 
$sql = ""; 
$sql .= "SELECT * FROM weeklytbakl"; 

if (isset($_POST['search'])) 
{ 
    $search_term = mysql_real_escape_string($_POST['searchbox']); 

    $sql .= " WHERE description = '{$search_term}'"; 
} 

$query = mysql_query($sql) or die(mysql_error()); 
?> 
+0

謝謝你的幫助!錯誤似乎已經消失,但是當我在搜索框中輸入內容並提交時,沒有任何內容正在顯示 – William1234

+0

嘗試將'description ='{$ search_term}''改爲'description LIKE'%$ search_term%'' – Suyog

+0

你是男人!非常感謝!一切正常! – William1234

1

$sql在哪裏宣佈?請正確地通過語法。

$sql .= " WHERE description = '{$search_term}'"; 

這應該是

$sql .= "SELECT * FROM your_table WHERE description = '{$search_term}'"; 

此外,當您正在搜索,先用LIKE

$sql .= "SELECT * FROM your_table WHERE description LIKE '%{$search_term}%'"; 
0

申報$ SQL變量之前添加空間,像下面的查詢語句的關鍵字。

$sql .= " WHERE description = '{$search_term}'";