I have a simple script, but it has just got a little more complex, at least for me.
so here it is, I need to request 2 menu buttons from table which contains all of them together. ID for both is known as it is already rendered by another script on the same page and wrapped in variables $cat_main_id
and $cat_add_id
. So here is my script, well at least a top part of it and my question is how I can get both menu buttons to be obtained by the same query, if that is actually possible?
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;
}
Yes easily, the key will be when you then get the results back to identify which row is which button
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"));
};
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"));
}
You could use an IN query like so:
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();
}
Similar to JimiDini's answer, but I prefer IN
instead of OR
. It doesn't make much difference for just two IDs, but if there were many of them I think it's much clearer to put them in a single list.
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"));
}