大家好,我试图创建一个php搜索页面,该页面将从mysql数据库中调出书籍列表,然后在单击书籍名称时调出与它们的关系表中的书籍列表。我在代码上有点挣扎,希望有人能够伸出援手
-这是我的搜索.php文件
<?php
$i=0;
$column_name = 'title'; // column to search by
$k =$_GET['k'];
$terms = explode(" ",$k);
//connect before calling mysql_real_escape_string
mysql_connect("localhost","","");
mysql_select_db("test");
$query ="SELECT id,title,author
FROM books WHERE";
foreach ($terms as $each){
$i++;
$each = '%' . $each . '%'; // add wildcard
$each = mysql_real_escape_string($each); // prevent sql injection
if($i==1)
$query .= " $column_name LIKE '$each' ";
else
$query .= " OR $column_name LIKE '$each' ";
}
echo 'QUERY: ' . $query;
$query = mysql_query($query) OR DIE(mysql_error());
//Code below is for using the relationships table assuming you have a column name id that
//references to the relationships table. Also, you should add a index on the column id.
$results = "";
while($row = mysql_fetch_array($query)) {
$results .= '<li>
<a href="book-relationships.php?id='.$row['relationshipid'].'">'.$row['title'].' author: '.$row['author'].'</a>
</li>';
}
$results = '<ul>' . $results . '</ul>';
echo $results;
删除 ";从这一行:
FROM books WHERE "; ";
您必须声明$i
$i = 0;
要防止 sql 注入,您可以使用:
foreach ($terms as $each){
$i++;
$each = '%' . $each . '%'; // add wildcard
$each = mysql_real_escape_string($each); // prevent sql injection
if($i==1)
$query .= " $keywords LIKE '$each' ";
else
$query .= " OR $keywords LIKE '$each' ";
}
此外,请确保用户无法将变量设置为不存在的表
完整代码
<?php
$i=0;
$column_name = 'title'; // column to search by
$k =$_GET['k'];
$terms = explode(" ",$k);
//connect before calling mysql_real_escape_string
mysql_connect("localhost","","");
mysql_select_db("test");
$query ="SELECT id,title,author
FROM books WHERE";
foreach ($terms as $each){
$i++;
$each = '%' . $each . '%'; // add wildcard
$each = mysql_real_escape_string($each); // prevent sql injection
if($i==1)
$query .= " $column_name LIKE '$each' ";
else
$query .= " OR $column_name LIKE '$each' ";
}
echo 'QUERY: ' . $query;
$query = mysql_query($query) OR DIE(mysql_error());
//Code below is for using the relationships table assuming you have a column name id that
//references to the relationships table. Also, you should add a index on the column id.
$results = "";
while($row = mysql_fetch_array($query)) {
$results .= '<li>
<a href="book-relationships.php?id='.$row['id'].'">'.$row['title'].' author: '.$row['author'].'</a>
</li>';
}
$results = '<ul>' . $ results . '</ul>';
echo $results;