我使用简单的表单进行数据库查询。数据库通过密码访问,密码已包含在代码中。我不确定为什么我一直在字符串转义和未定义的变量 $ query = htmlspecialchars($ query);
上遇到错误<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form action="Search2.php" method="POST">
<input type="text" name="query" />
<input type="submit" value="Search" />
</form>
<?php
if (isset($_POST['query']))
$query = $_POST['query'];
if (!empty($query))
$query = $_POST['query'];
// gets value sent over search form
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
$raw_results = mysql_query("SELECT LastName, FirstName FROM Staff
WHERE (`LastName` LIKE '%".$query."%') OR (`FirstName` LIKE '%".$query."%')") or die(mysql_error());
if(mysql_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
// $results = mysql_fetch_array($raw_results) puts data from database into array, while it's valid it does the loop
echo "<p><h3>".$results['LastName']."</h3>".$results['FirstName']."</p>";
// posts results gotten from database(title and text) you can also show id ($results['id'])
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
</body>
</html>
答案 0 :(得分:2)
此处的问题是您已使用凭据调用mysqli
对象,但稍后您尝试使用mysql_
程序方法执行。你在那里没有联系。您需要坚持使用mysqli
对象。此外,您应该使用预准备语句来处理有关SQL查询的用户输入。
删除这些,我们不需要为准备好的陈述进行消毒:
//BYE!
$query = htmlspecialchars($query);
// changes characters used in html to their equivalents, for example: < to >
$query = mysql_real_escape_string($query);
// makes sure nobody uses SQL injection
现在让我们使用mysqli对象和OOP编写的方法。但是,首先我们需要构建我们的类似语句,因为我们的查询变量没有被执行,您不能将%?%
直接连接到prepared()
语句中。
$query = '%'.$query.'%';
$stmt = $mysqli->prepare("SELECT LastName, FirstName FROM Staff
WHERE LastName LIKE ? OR FirstName LIKE ?");
现在我们可以将参数绑定到$stmt
对象。
$stmt->bind_param('ss', $query, $query);
让我们现在执行它并获取我们的数据。
$result = $stmt->execute();
然后我们可以循环:
while ($row = $result->fetch_assoc()) {
echo "<p><h3>".$result['LastName']."</h3>".$result['FirstName']."</p>";
}
修改强>
您也不需要使用反引号来转义列名,因为:
-
名称答案 1 :(得分:0)
确保您的PHP版本低于7.0,如此处所述:
http://php.net/manual/en/function.mysql-real-escape-string.php
警告 此扩展在PHP 5.5.0中已弃用,并且已在PHP 7.0.0中删除。相反,应该使用MySQLi或PDO_MySQL扩展。另请参阅MySQL:选择API指南和相关的常见问题解答以获取更多信息。该功能的替代方案包括: mysqli_real_escape_string() PDO ::引号()