0

我有一个脚本,它应该根据搜索输入从 mysql 表中返回值。该脚本由两个文件组成。

搜索.php

<?php
if ( isset( $_GET['s'])) {
require_once( dirname( __FILE__ ) . '/class-search.php' );
$search = new search();
$search_term = $GET['s'];
$search_results = $search->search($search_term);
}
?>
<!DOCTYPE html>
<html>
<head>
    <title>Search</title>
</head>
<body>
    <h1>Search</h1>
    <div class="search-form">
        <form action="" method="get">
            <div class="form-field">
                <label for="search-field">Search</label>
                <input type="search" name="s" placeholder="Search by name" results="5" value="<?php echo $search_term; ?>">
                <input type="submit" value="Search">
            </div>
        </form>
    </div>
    <?php if ( $search_results ) : ?>
    <div class="results-count">
        <p><?php echo $search_results['count']; ?> results found</p>
    </div>
    <div class="results-table">
        <?php foreach ( $search_results['results'] as $search_result ) : ?>
        <div class="result">
            <p><?php echo $search_result->title; ?></p>
        </div>
        <?php endforeach; ?>
    </div>
    <div class="search-raw">
        <pre><?php print_r($search_results); ?></pre>
    </div>
    <?php endif; ?>
</body>

和类-search.php

<?php
class search {

private $mysqli;
public function __construct() {
    $this->connect();
}
private function connect() {
    $this->mysqli = new mysqli('HOST', 'USERNAME', 'PASSWORD', 'DATABASE' );
}
public function search($search_term) {
    $sanitized = $this->mysqli->query("
    SELECT * FROM `Apple`
    FROM search
    WHERE Last_Name LIKE '%{$sanitized}%'
    ");
    if ( ! $query->num_rows ) {
        return false;
    }
    while( $row = $query->fetch_object() ) {
        $rows[] = $row;
    }
    $search_results = array(
    'count' => $query->num_rows,
    'results' => $rows,
    );
    return $search_results;
}
}
?>

在我的数据库中,我有两个表,但我只对搜索一个(Apple)的内容感兴趣。有人可以帮助我吗?我似乎无法完成这项工作。无论我搜索什么,都不会返回任何结果。截至目前,我只使用 Last_Name 标准,但我想添加其他标准。这是我的表格截图的链接http://imgur.com/a/H3DnG

我真的很感激任何可能的反馈。谢谢你。

4

1 回答 1

1

如果再次检查,

搜索方法中,您$search_term作为参数传递,但在您使用$sanitized的查询中,在执行查询之前不存在。

您的结果集在$sanitized中,但您正在检查$query是否存在甚至不存在的num_rows 。此外,您正在false使用该方法返回,因此您无法识别实际问题。

public function search($search_term) {
    $sanitized = $this->mysqli->query("
    SELECT * FROM `Apple`
    FROM search
    WHERE Last_Name LIKE '%{$search_term}%'
    ");
    if ( ! $sanitized->num_rows ) {
        //return false;
        retrun [];
    }
    $rows  = [];
    while( $row = $sanitized->fetch_object() ) {
        $rows[] = $row;
    }
    $search_results = array(
    'count' => $query->num_rows,
    'results' => $rows,
    );
    return $search_results;
}

connect 方法中,添加这将告诉它是否连接到数据库。

if ($this->mysqli->connect_errno) {
    printf("Connect failed: %s\n", $this->mysqli->connect_error);
    exit();
}
于 2016-11-06T08:10:58.437 回答