使用 $_GET ID 在 PHP 中过滤mysql_fetch_array


using a $_GET id to filter a mysql_fetch_array in PHP

所以我有一个查询,我正在将所有项目返回到一个mysql_fetch_array中。现在,我知道我可以编写另一个查询,只需将我需要的项目选择到单独的查询中,但是,有没有办法从更大的查询中过滤我想要的依赖于 $_GET 的内容?

因此,在英语中,用户来自一个具有 ?id=1 的超链接,我花了一段时间来获取所有值,但只在列表中显示 $_GET['id'] 项

<?php //give ma all values but only echo out list of the $_GET['id'] in the url
  while ($row = mysql_fetch_array($result) {
    $id = $rowvideo["id"];
    $title = $rowvideo["title"];
    $length = $rowvideo["length"];
}
echo("<li><a href='#'>". $title." " .$length. "</a></li>");
?>

希望这是有道理的。谢谢大家。

如果您不希望第二个查询获得所需的内容,则循环中的简单if-statement应该可以工作:

<?php
$getId = isset($_GET['id']) ? $_GET['id'] : false;
//give ma all values but only echo out list of the $_GET['id'] in the url
while ($row = mysql_fetch_array($result)) {
    $id = $row["id"];
    $title = $row["title"];
    $length = $row["length"];
    if ($id == $getId) {
        echo("<li><a href='#'>". $title." " .$length. "</a></li>");
    }
}
?>

请注意,我在循环外部声明了$getId,以防止在每次迭代期间都必须使用isset()。如果您不验证它是否已设置并尝试使用它,它将引发undefined index警告 - 假设您已打开error_reporting(启用该级别)。

或者,您可以在解析完所有数据后对数据使用 PHP 的array_filter()

$results = array();
while ($row = mysql_fetch_array($result)) $results[] = $row;
if (isset($_GET['id'])) {
    $filtered = array_filter($results, function($element) use ($_GET['id']) { return ($element['id'] == $_GET['id']); });
    $results = $filtered;
}
foreach ($results as $result) {
    echo("<li><a href='#'>". $result['title']." " .$result['length']. "</a></li>");
}

我个人的意见是提高效率并编写第二个查询,当然假设您在指定id时实际上并不需要所有结果。它会像这样简单:

if (isset($_GET['id']) && is_numeric($_GET['id'])) {
    $query = 'SELECT id, title, length FROM table WHERE id=' . (int)$_GET['id'];
} else {
    $query = 'SELECT id, title, length FROM table';
}
// your existing code as-is

这里更清楚一点:

这将允许通过指定 id=xxx 在 url 中按 id 进行筛选,如果 xxx 是一个正整数。所以 id 的 'bob' 或 -1 不会过滤结果,仍然给出所有结果

$filter=false;
if(isset($_GET['id']))
{
    $filter_id=intval($_GET['id']);
    if($id>0) $filter=true;
}
while($row = mysql_fetch_array($result))
{
    if( (!$filter) || ( ($filter) && ($filter_id==$row['id']) ) )
    {
        $id = $row["id"];
        $title = $row["title"];
        $length = $row["length"];
        // do other stuff here
    }
}

我还将$rowvideo更改为$row,因为这是您用于获取结果的数组。

<?php //give ma all values but only echo out list of the $_GET['id'] in the url
  while ($row = mysql_fetch_array($result)) {
    $id = $rowvideo["id"];
    $title = $rowvideo["title"];
    $length = $rowvideo["length"];
    if ($id == $_GET['id']) { // or even ===
      echo("<li><a href='#'>". $title." " .$length. "</a></li>");
    }
  }
?>