0

再会,

我在使用以下 php 代码时遇到了很多麻烦,它的伪代码如下:

检查表中是否存在关系,如果不存在,则将关系添加到表中。否则获取当前关系并返回它。

代码如下:

    $result = mysql_query("SELECT * FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id = '" .$other. "')");
if($result == false){
    mysql_query("INSERT INTO `friends`(`user_id`, `user_id2`, `status`) VALUES ('" .$me. "', '" .$other. "', 'pending')");
    echo("Friend Request Sent"); 
}
else{
    $res = mysql_query("SELECT 'status' FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "')");
    $rows = array();
    while($r = mysql_fetch_assoc($res)) {
        $rows[] = $r;
    }
    echo json_encode($rows); 

}

提前致谢

4

1 回答 1

1

如果条件,您应该尝试以下方法

if(mysql_num_rows($result)){
     mysql_query("INSERT INTO `friends`(`user_id`, `user_id2`, `status`) VALUES ('" .$me. "', '" .$other. "', 'pending')");
     echo("Friend Request Sent"); 
}

并且 else 块应该与第一个查询相同,它应该看起来像

else{
    $res = mysql_query("SELECT 'status' FROM friends WHERE (user_id = '" .$me. "' AND user_id2 = '" .$other. "') OR (user_id2 = '" .$me. "' AND user_id = '" .$other. "')") ;
    $rows = array();
    while($r = mysql_fetch_assoc($res)) {
       $rows[] = $r;
    }
    echo json_encode($rows); 
}
于 2012-10-18T19:03:15.693 回答