php 搜索作为单独的页面工作,但不在同一页面上

标签 php html mysql search

我正在开发一个项目,我可以在 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/

相关文章:

php - 通过更改查询字符串参数在 Symfony2 中进行简单重定向,与路由无关

php - #php - "page expire"而不是 "session expire"

javascript - 使用 jquery 搜索,无需提交按钮

html - 使用伪类来减少背景图像而不是文本的不透明度

mysql - 使用mysql增量更新返回重复键错误

php - 创建 Joomla 用户配置文件插件

php - 修补 PHP 5.3.10 以支持 sybase_next_result()

php - mySQL 中的默认日期时间格式

html - 如何处理放大时 div 严重变形的问题?

asp.net (mvc) 和 mysql,我要进入这里做什么?