我将SQL搜索嵌入到PHP代码中,如下所示:
<?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>
但是代码给了我以下错误:
您的SQL语法有错误;检查手册 对应于您的MySQL服务器版本,以便使用正确的语法 在第1行'WHERE description ='''附近
您能否帮我确定一下它无法正常运作的原因?
答案 0 :(得分: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}%'";
答案 1 :(得分: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());
?>
答案 2 :(得分:0)
首先声明$ sql变量,然后在查询语句中的where关键字之前添加空格,如下所示。
$sql .= " WHERE description = '{$search_term}'";