PHP数据库搜索显示


PHP Database search display

让你了解我在做什么。我正在做一个项目,在我的学校校园里,你可以导航。例如,一个房间可以被称为J2626或J2617等等……事情是,当一个用户使用我的网站,我只希望它在房间的确切名称键入能够显示任何东西。现在它不像我想的那样好用。例如:如果你只在搜索栏中输入J,它会显示所有以J开头的房间

下面是我现在的代码:

<?php
$fileName = dirname(dirname(__FILE__)) . "../../db/bth_nav.sqlite";
if (isset($_GET['page'])) {
    $argument = $_GET['page'];
    $argument = "%" . $argument . "%";
    $db = new PDO("sqlite:$fileName");
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
    $stmt = $db->prepare('SELECT * FROM bth_nav WHERE name LIKE (:nameOwner) OR owner LIKE (:nameOwner);');
    $stmt->execute(array($argument));
    $res = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (empty($res)) {
        header("Location: " . "http://" . $_SERVER['index.php']);
    }
?>
<div class = "formObjectSearch">
    <?php foreach ($res as $val) { ?>
            <div class = "infoTab">
                <h2><?= $val['name']; ?></h2>
                <p>Guidance: <?= $val['info']; ?></p>
                <p>Whos sitting here?: <?= $val['owner']; ?>
            </div>
            <img class = "buildingImage" src = "img/<?= $val['image']; ?>"
                <?php
      }
}
                ?>
    </div>

我尝试了不同的if语句,但没有成功。所以我需要帮助的是,我只希望用户能够搜索正确的房间名,而不是只搜索J并显示所有内容。

这是我的index.php:

我使用这个链接,因为代码样本不希望工作:

Here is my building.php:

同样在这里:building.php code

和新的search.php的帮助:

此处相同:search.php code

我现在得到这些错误:

注意:未定义的索引:index.php在/path/incl/files/search.php第19行

警告:无法修改报头信息-报头已经由(output started at/path/incl/header.php:7)在/path/incl/files/search.php第19行

My header.php code:

此处相同:header.php code

我的config.php代码:

config.php代码

我的footer.php代码:

如果我理解正确,如果你想搜索所有以J开头的房间,你需要改变你的参数。

解释:

'%J%' -搜索所选字段,其中为J字母。

'%J' -搜索所选字段,其中J为最后一个字母。

'J%' -搜索所选字段,其中J是第一个字母。

试着这样改变你的参数:

$argument = $argument . "%";

修复if语句:

if (empty($res) OR $res == null) {
   header('Location: http://'.$_SERVER['index.php']);
}
else {
   echo '<div class = "formObjectSearch">';
   foreach ($res as $val) {
        echo '<div class = "infoTab">';
        echo '<h2>'.$val["name"].'</h2>';
        echo '<p>Guidance:'.$val["info"].'</p>';
        echo '<p>Whos sitting here?:'.$val["owner"].'</p>';
        echo '</div>';
        echo '<img class="buildingImage" src="img/'.$val['image'].'" />';
   }
   echo '</div>';
}

你可以试着用:

if ($res->rowCount() > 0) {
  // if founded
} else {
  // header('Location: http://'.$_SERVER['index.php']);
}