0

我有一个简单的脚本,但它变得更复杂了,至少对我来说是这样。

所以在这里,我需要从包含所有它们的表中请求 2 个菜单按钮。两者的 ID 都是已知的,因为它已经由同一页面上的另一个脚本呈现并包装在变量$cat_main_id$cat_add_id. 所以这是我的脚本,至少是它的顶部,我的问题是如何让两个菜单按钮通过同一个查询获得,如果这实际上可能的话?

    if ($cat_main_id > 0) {
    $menu_query = 'SELECT * FROM lcategories WHERE ID in ( :id , :id2 )';
    $res = $db->prepare($menu_query);
    $res->execute(array(':id' => $cat_main_id, ':id2' => $cat_add_id));
    foreach ($res as $info);
} else {
    echo '';
}
while ($info = $res -> fetch()){
    $category_name = str_replace("&", "&", $info['category_name']);
    $category_page = $info['category_page'];
    $category_dir = $info['category_folder'];
    $category_link = DS.$category_dir.DS.$category_page;
print<<<END

<div class="post_cat">Posted in category <a href="$category_link" class="cat">$category_name</a> <a href="$category_link" class="cat">$category_name</a></div>
<div class="clear"></div>

END;
}
4

4 回答 4

1

是的,很容易,关键是当您返回结果以确定哪一行是哪个按钮时

if($cat_main_id > 0 && $cat_add_id > 0){
  $menu_query = 'SELECT * FROM lcategories WHERE ID in ( :id , :id2 )';
  $res = $db->prepare($menu_query);
  $res->execute(array(':id' => $cat_main_id, ,':id2' => $cat_add_id));
}else{
  die(header("Location: error.php"));
};
于 2013-07-24T16:40:10.530 回答
0

您可以像这样使用 IN 查询:

if ($cat_main_id > 0)
{
  $menu_query = 'SELECT * FROM lcategories WHERE ID IN (:id1, :id2)';
  $res = $db->prepare($menu_query);
  $res->execute(array(':id1' => $cat_main_id, ':id2' => $cat_add_id));
}
else
{
  header("Location: error.php");
  die();
}
于 2013-07-24T16:39:01.503 回答
0

类似于 JimiDini 的回答,但我更喜欢IN而不是OR. 仅两个 ID 并没有太大区别,但如果它们中有很多,我认为将它们放在一个列表中会更清楚。

if ($cat_main_id > 0) {
    $menu_query = 'SELECT * FROM lcategories WHERE ID IN (:id, :id2)';
    $res = $db->prepare($menu_query);
    $res->execute(array(':id' => $cat_main_id, ':id2' => $cat_add_id));
} else {
    die(header("Location: error.php"));
}
于 2013-07-24T16:39:30.060 回答
0
if ($cat_main_id > 0) {
    $menu_query = 'SELECT * FROM lcategories WHERE ID = :id OR ID = :id2';
    $res = $db->prepare($menu_query);
    $res->execute(array(':id' => $cat_main_id, ':id2' => $cat_add_id));
} else {
    die(header("Location: error.php"));
}
于 2013-07-24T16:37:09.197 回答