Peter通过单击Michelle页面上的“添加朋友”按钮向数据库发送请求,数据库表tbl_frienRequest将Peter存储在“user”,并将Michelle存储在“targetuser”。
当米歇尔访问彼得的页面时,彼得的页面不得显示“添加朋友”按钮。当彼得访问米歇尔页面时,米歇尔的页面也不得显示“添加朋友”按钮。
如何编写if else语句以显示或不显示其页面上的“添加朋友”按钮? 目前我正在使用这种方法:
$query111 = "SELECT id FROM tbl_frienRequest WHERE user='{$username1}' AND targetuser='{$username2}'";
$result111 = mysql_query($query111,$connection) or die (mysql_error());
confirm_query($result111);
$requestCount = mysql_num_rows($result111);
$query2 = "SELECT id FROM tbl_frienRequest WHERE user='{$username2}' AND targetuser='{$username1}'";
$result2 = mysql_query($query2,$connection) or die (mysql_error());
confirm_query($result2);
$requestCount2 = mysql_num_rows($result2);
if (($requestCount == 0) or ($requestCount2 == 0)){
//show "add friend" button.
}
我认为它有效,但代码很长,有没有其他缩短代码来获得相同的输出?
答案 0 :(得分:2)
$query111 = "SELECT id FROM tbl_frienRequest WHERE user in('{$username1}','{$username2}') AND targetuser in ('{$username2}','{$username2}' )";
答案 1 :(得分:1)
您可以在查询中使用OR条件: 即:
SELECT id
FROM tbl_frienRequest
WHERE (USER='{$username1}'
AND targetuser='{$username2}')
OR ( USER='{$username2}'
AND targetuser='{$username1}'
试试这个:
$query111 = "SELECT id FROM tbl_frienRequest WHERE (user='{$username1}' AND targetuser='{$username2}') OR ( user='{$username2}' AND targetuser='{$username1}')";
$result111 = mysql_query($query111,$connection) or die (mysql_error());
confirm_query($result111);
$requestCount = mysql_num_rows($result111);
if ($requestCount == 0){
//show "add friend" button.
}
答案 2 :(得分:1)
$query111 = "SELECT id FROM tbl_frienRequest WHERE (user='{$username1}'
AND targetuser='{$username2}')
OR user='{$username2}' AND targetuser='{$username1}'";
答案 3 :(得分:1)
我不确定我完全理解;你只想要一个会返回两个选项的查询?试试这个:
$sql = "SELECT id FROM tbl_frienRequest
WHERE (user='{$username1}' AND targetuser='{$username2}')
OR
(user='{$username2}' AND targetuser='{$username1}')";
这将返回两个选项;唯一的潜在技巧是找出哪个是哪个(如果两个都返回结果)。
答案 4 :(得分:1)
$query = "SELECT id FROM tbl_frienRequest WHERE user='{$username1}' AND targetuser='{$username2}' OR user='{$username2}' AND targetuser='{$username1}' " ;
AND优先于OR,因此您将通过此一个查询获得所需的结果