【问题标题】:php search works as seperate page, but not on same pagephp搜索作为单独的页面工作,但不在同一页面上
【发布时间】:2017-05-19 04:03:21
【问题描述】:

我正在做一个项目,我可以在一个 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); 的解析错误,有什么想法吗?

【问题讨论】:

  • 您的代码易受 SQL 注入攻击,您需要修复此问题。

标签: php html mysql search


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-09
    相关资源
    最近更新 更多