我已经与这段代码作斗争有一段时间了,需要一些建议。我创建了一个计算机游戏的 mysql 数据库以及一个简单的搜索框和表单内的按钮。如果我输入有关游戏名称或其描述的任何关键字,php 应该在下拉列表中回显结果(因为可能有多个“点击”)。目前,我只是在页面底部显示结果。我的查询愉快地运行 else 语句并向我显示提供的所有游戏,但当我输入搜索条件时没有得到任何结果,也没有错误消息。 print_r($q) 也绘制一个空白。出了什么问题? 注意。此时我不太担心代码注入(inject) - 一次一小步!非常感谢
<!DOCTYPE HTML>
<HTML>
<head></head>
<?php
//Connect to the Database
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "Secret";
$dbname = "gaming";
//Create connection
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Show error if connection fails
if (!$conn){
die("Connection failed: " .
mysqli_connect_error());
}
if(isset($_REQUEST['submit'])){
$search=$_POST['search'];
$sql="SELECT* FROM gamestbl WHERE game_name LIKE '%.$search.%' OR game_description LIKE '%.$search.%'";
$q=mysqli_query($conn,$sql);
}
else{
$sql="SELECT* FROM gamestbl";
$q=mysqli_query($conn,$sql);
}
?>
<body>
<form method="post">
<table width="200" border="1">
<tr>
<td>Search</td>
<td><input type="text" name="search" value="" /></td>
<td><input type="submit" name="submit" value=" Find " /></td>
</tr>
</table>
</form>
<table>
<tr>
<td>Game ID</td>
<td>Game Name</td>
<td>Game Description</td>
<td>Game Genre</td>
<td>Game Price</td>
</tr>
<?php
print_r($q);
while($res=mysqli_fetch_array($q)){
?>
<tr>
<td><?php echo $res['game_id'];?></td>
<td><?php echo $res['game_genre'];?></td>
<td><?php echo $res['game_name'];?></td>
<td><?php echo $res['game_description'];?></td>
<td><?php echo $res['game_price'];?></td>
</tr>
<?php }?>
</table>
</body>
</html>
<?php
// get rid of data in cache and close
mysqli_close($conn);
?>
最佳答案
改变
$sql="SELECT* FROM gamestbl WHERE game_name LIKE '%.$search.%' OR game_description LIKE '%.$search.%'";
对于
$search = mysql_real_escape_string($search); // Prevent from injection
$sql = sprintf("SELECT * FROM gamestbl WHERE concat(game_name, game_description) LIKE '%s'", '%' . $search . '%');
sprintf 是在字符串中添加变量的更好方法,而 concat 可以通过避免“OR”来使 SQL 更短。
关于php - 无法使用LIKE使用php从mysql中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28451828/