PHP搜索功能无法连接到MySQL

时间:2016-06-20 16:36:15

标签: php mysql mysqli

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

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

的search.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);

?>

1 个答案:

答案 0 :(得分:0)

$title$desc未定义,因此您有空<h3>和空<p>标记。

此外,我认为在代码中进行一些更改会更好。

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

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