【问题标题】:How do I output more search results from Mysql database?如何从 Mysql 数据库中输出更多搜索结果?
【发布时间】:2016-12-22 22:26:50
【问题描述】:

我有一个用 PHP 制作的 HTML 搜索表单,它连接到 MySQL 数据库,找到一个包含列和行的表,然后在表下显示这些数据并带有回显。

$output = "Document ID: ".$results['id']."<br><a href='".$results['url']."'>".$results['name']."</a> (".$results['short_withtag'].")<br><span style='font-size: 12px;'>Bad search result? Try a different keyword</span>

这些列是 id、name、short、short_withtag 和 url,每个都包含特定的数据。问题是,如果我输入 pie 之类的关键字(所有行中都存在这样的术语),它将只显示一个搜索结果。如何让它显示多个?

这是我使用的查询:

mysql_query("SELECT * FROM env
WHERE (`id` LIKE '%".$query."%') OR (`name` LIKE '%".$query."%') OR (`short` LIKE '%".$query."%') OR (`short_withtag` LIKE '%".$query."%') OR (`url` LIKE '%".$query."%')") or die(mysql_error());

【问题讨论】:

  • 发布您正在使用的 MySQL 查询。
  • 好的,我编辑了我的帖子。
  • 您需要将查询结果放入一个数组中,然后每次循环添加到您的 $output 变量。您当前只是存储结果集的第一行。

标签: php mysql database


【解决方案1】:

只需将所有行放入一个数组中,然后使用 foreach 循环将它们输出。

你可以这样做:

$result = mysql_query("SELECT * FROM env
WHERE (`id` LIKE '%".$query."%') OR (`name` LIKE '%".$query."%') OR (`short` LIKE '%".$query."%') OR (`short_withtag` LIKE '%".$query."%') OR (`url` LIKE '%".$query."%')") or die(mysql_error());

// If query is successful
if ($result) {

    // Create an empty array to which we're going to put rows
    $dataForTheOutput = array();

    // Now push each row into the array
    while ($row = mysql_fetch_assoc($result)) {

        array_push($dataForTheOutput, $row);

    }

    // Now you can output data

    if (empty($dataForTheOutput)) {

        echo 'No results found';

    } else {

        // Using foreach loop display each row
        foreach ($dataForTheOutput as $component) {

            echo "Document ID: ".$component['id']."<br><a href='".$component['url']."'>".$component['name']."</a> (".$component['short_withtag'].")<br><span style='font-size: 12px;'>Bad search result? Try a different keyword</span>

        }

    }

}

请注意,这是一种非常过时且不太安全或可维护的做事方式。

【讨论】:

    猜你喜欢
    • 2018-08-27
    • 2015-03-09
    • 2019-01-08
    • 2014-06-23
    • 2018-05-02
    • 2018-12-10
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多