【问题标题】:PHP Search function unable to connect to MySQLPHP搜索功能无法连接到MySQL
【发布时间】:2016-06-20 16:36:15
【问题描述】:

我正在尝试在本地服务器上为我的网站创建一个搜索栏,但是当我提交时,生成的页面只是空白。我一直在关注一些在线指南,但似乎无法弄清楚为什么它没有连接到我的 MySQL 数据库并获得结果。这是我第一次尝试 db 和 PHP,感谢所有建议。

<form action="./search.php" method="get">
        <input type="text" name="q">
        <input type="submit" value="Search">
</form>

搜索.php

<?php

    $conn = mysqli_connect("localhost", "root", "root", "womendig_search");

    if(mysqli_connect_errno()){
        echo "Failed to connect: " . mysqli_connect_error(); 
    }

    error_reporting(0);

    $output = '';

    if(isset($_GET['q']) && $_GET['q'] !== ' '){
        $searchq = $_GET['q'];

        $q = mysqli_query($conn, "SELECT * FROM search WHERE keywords LIKE '%$searchq%' OR title LIKE '%$searchq%'") or die(mysqli_error());
        $c = mysqli_num_rows($q);
        if($c == 0){
            $output = 'No search results for <b>"' . $searchq . '"</b>';
        } else {
            while($row = mysqli_fetch_array($q)){
                $id = $row['id'];
                $city = $row['city'];
                $country = $row['country'];
                $descriptions = $row['descriptions'];

                $output .= '<h3>' . $title . '</h3>
                                <p>' . $desc . '</p>
                            ';
            }
        }
    } else {
        header("location: ./");
    }
    print("$output");
    mysqli_close($conn);

?>

【问题讨论】:

  • 空白页通常是一个错误。你检查过你的错误日志吗?您也对 SQL 注入持开放态度,这可能会导致您的查询失败,因为它会无效..
  • 所以在您的$output 中,您附加了$title$desc。这些在哪里设置?

标签: php mysql mysqli


【解决方案1】:

$title$desc 未定义,因此您有空的 &lt;h3&gt; 和空的 &lt;p&gt; 标签。

另外,我认为最好对您的代码进行一些更改。

使用!empty($_GET['q']) 代替$_GET['q'] !== ' ' 并使用extract($row); 代替

$id = $row['id'];
$city = $row['city'];
$country = $row['country'];
$descriptions = $row['descriptions'];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-04
    • 2015-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 2019-04-03
    • 1970-01-01
    相关资源
    最近更新 更多