我正在开发一个项目,我可以在 html 页面上使用多个表单来搜索和更新 mysql 数据库中的表。我创建了一个基本的 html 表单,它将在单独的 php 文件上运行搜索。当我尝试将相同的 php 脚本集成到相同的 html 中时,它没有找到任何结果。任何帮助将不胜感激。
基本 html
<html>
<body>
<form name="search" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50" />
<input type="submit" name="Submit" value="Search" />
</form>
</body>
</html>
搜索 php
<?php
$database = "dbname";
$username = "name";
$password = "pass";
$host = "host";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error){
die("Failed:" . $conn->connect_error);
}
echo"Successful";
$query = $_POST['search'];
$query = htmlspecialchars($query);
$raw_results = mysqli_query($conn,"SELECT * FROM beers WHERE name LIKE '%".$query."%'");
if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysqli_fetch_array($raw_results)){
echo "<p><h3>".$results['Name']."</h3>".$results['Brewery']."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
这是分开工作的,但是如果我复制相同的 php 脚本并将其插入到主 html 中,它会连接但找不到结果。尝试使用 _GET
而不是 _POST
删除了操作字段,并且我已经搜索了所有类似的问题。如果我完全缩小所有内容,则会出现 $query = htmlspecialchars($query);
的解析错误,有什么想法吗?
最佳答案
应用if (isset($query)) {...}
。只有搜索名称有效才能获得结果。
<?php
$query = $_POST['search'];
// Apply validation.
if (isset($query)) {
$query = htmlspecialchars($query);
echo"Successful";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Failed:" . $conn->connect_error);
}
$raw_results = mysqli_query($conn, "SELECT * FROM beers WHERE name LIKE '%" . $query . "%'");
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($results = mysqli_fetch_array($raw_results)) {
echo "<p><h3>" . $results['Name'] . "</h3>" . $results['Brewery'] . "</p>";
}
} else { // if there is no matching rows do following
echo "No results";
}
}
?>
关于php 搜索作为单独的页面工作,但不在同一页面上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44061254/