首页 > 解决方案 > 如何在php中获取搜索结果

问题描述

当我通过查询时,我无法从数据库中获取结果。我的问题是,当用户在其上键入一些值时input,会将值传递给操作。但我的功能不起作用。并通过以下错误:

Fatal error: Call to a member function fetch_assoc() on boolean in D:\e.batgerel\development\projects\travelagency\includes\functions.php on line 409

这是我的代码示例:

<form action="search.php?search=<?php echo $_GET['search']; ?>" method="GET">
    <input type="text" name="search" placeholder="Хайлт хийх" aria-label="search_input"/ >
    <button type="submit">
       <i class="fa fa-search"></i>
    </button>
</form>

我的search.php

<?php require_once 'includes/config.php';

    if(isset($_GET['search'])) {
      $search = $_GET['search'];
      search($search);
    } else {
      header('Location: index.php');
    }
?>
<?php include 'layouts/header.php'; ?>
<?php include 'layouts/footer.php'; ?>

和功能:

function search($search) {
    global $conn;

    $sql = "SELECT * FROM travels WHERE title LIKE '%$search%' OR description LIKE '%$search%'";

    $result = $conn -> query($sql);
    $list = array();

    while($row = $result->fetch_assoc()) {
        $list[] = $row;
    }
    return $list;
}

有什么解决办法吗?我做错了什么 ?谢谢你。

标签: phpmysql

解决方案


mysqli::query 在失败时返回 FALSE:http: //php.net/manual/en/mysqli.query.php#refsect1-mysqli.query-returnvalues

因此,您需要首先确保结果不是 FALSE:

if ($result = $conn->query($sql)) {
    // here result processing
} else {
    // here error handling
}

推荐阅读