[英]Multiple if and elseif don't work properly
要求用戶選擇位置和菜餚以搜索附近的餐館。 現在,如果用戶只選擇特定的美食,所有帶有美食的餐廳都應該從數據庫和相同的案例位置中選擇...這里只是回聲第一部分而不是其他兩個條件..請幫助!! 請不要考慮注射
下面給出了用戶重定向的php部分..
<?php
if(isset($_REQUEST['location']) && $_REQUEST['cuisine'])
{
$sql="SELECT * FROM `restaurant` WHERE `location_id`='".$_REQUEST['location']."' and `cuisine_id`='".$_REQUEST['cuisine']."' ORDER BY restaurant_name ";
echo"qu";
}
elseif(isset($_REQUEST['location']) && $_REQUEST['cuisine'] ='all cuisine')
{
$sql="SELECT * FROM `restaurant` WHERE `location_id`='".$_REQUEST['location']."' ORDER BY restaurant_name ";
echo"here are result";
}
elseif(isset($_REQUEST['cuisine']) && $_REQUEST['location'] ='all location')
{
$sql="SELECT * FROM `restaurant` WHERE `cuisine_id`='".$_REQUEST['cuisine']."' ORDER BY restaurant_name ";
echo"query";
}
else
{
echo"no result found";
}
?>
$_REQUEST['cuisine'] ='all cuisine'
應該
$_REQUEST['cuisine'] == 'all cuisine'
if ($a= 'a')
將返回true,則不會進行比較。
如果你想比較它必須
if($a == 'a')
所以這是一個例子
$a = 'b';
if($a = 'a'){
echo 'here';
}else{
echo 'not here';
}
這將here
輸出
為了讓$_REQUEST['cuisine']
等於“所有美食”,變量$_REQUEST['cuisine']
將首先需要設置。 同上位置。
因此,只要$_REQUEST['cuisine'] === 'all cuisine'
都是真的(同樣位置), isset($_REQUEST['cuisine'])
將是真的,這就是為什么這兩種情況永遠不會發生的原因 -它們都被isset($_REQUEST['location'] && $_REQUEST['cuisine'])
搶占isset($_REQUEST['location'] && $_REQUEST['cuisine'])
。
我想你要找的是:
<?php
if(isset($_REQUEST['location'], $_REQUEST['cuisine']))
{
if($_REQUEST['cuisine'] === 'all cuisine')
{
$sql="SELECT * FROM `restaurant` WHERE `location_id`='".$_REQUEST['location']."' ORDER BY restaurant_name ";
echo"here are result";
}
elseif($_REQUEST['location'] === 'all location')
{
$sql="SELECT * FROM `restaurant` WHERE `cuisine_id`='".$_REQUEST['cuisine']."' ORDER BY restaurant_name ";
echo"query";
}
else
{
$sql="SELECT * FROM `restaurant` WHERE `location_id`='".$_REQUEST['location']."' and `cuisine_id`='".$_REQUEST['cuisine']."' ORDER BY restaurant_name ";
echo"qu";
}
}
else
{
echo"no result found";
}
?>
PS:其他評論, http : //php.net/ternary也值得注意。
Single =
指定一個值,而如果左側的值等於右側的值,則==
返回true。
我想這樣做:
// field name in DB => field name in REQUEST
$fields = array('location_id'=>'location', 'cuisine_id'=>'cuisine');
$cond = array();
foreach($fields as $f=>$p) {
$v = isset($_REQUEST[$p]) ? mysql_real_escape_string($_REQUEST[$p]) : null;
if($v && $v!=="all $p") {
$cond[] = "`$f`='$v'";
}
}
$sql = "SELECT * FROM `restaurant` WHERE " . join(' AND ', $cond) . " ORDER BY restaurant_name";
// execute $sql query
// ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.