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

时间:2017-05-19 04:03:22

标签: 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脚本并将其插入主连接,但它没有找到任何结果。尝试使用_GET而不是_POST删除了操作字段,并且我已经搜索了类似的问题。如果我将所有内容完全缩小,它会给$query = htmlspecialchars($query);一个解析错误,任何想法?

1 个答案:

答案 0 :(得分:0)

申请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";
    }
}
?>