我有这个问题:
function find_Friends($UserID){
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!$mysqli) {
die('There was a problem connecting to the database.');
}
$query="SELECT * FROM Friends WHERE UserID = '$UserID' OR FriendID = '$UserID'";
$result = $mysqli->query($query);
//List all relevant
while($row = $result->fetch_row()) {
//Do logic
}
$mysqli->close();
}
所以假设查询是这样的:
SELECT * FROM Friends WHERE UserID = '123' OR FriendID = '123'
我的查询返回以下内容:
UserID | FriendID
123 | 456
我的问题是,如何在php中返回FriendID 456? 我基本上只想返回不是查询号码的列,在本例中为123。
所以,如果我正在寻找8434而且我得到了回报:
UserID | FriendID
2356 | 8434
我想要返回UserID,而不是FriendID,但在原始查询中我想要返回FriendID。
我如何在php / mysql中执行此操作?
答案 0 :(得分:1)
如果您只关心数字而不关心它是哪一列,您可以将查询更改为:
SELECT IF(UserID='123',FriendID,UserID) AS Number FROM Friends WHERE UserID = '123' OR FriendID = '123'
或者,如果你关心它是哪一个,那么保持查询字符串不变并应用这个PHP:
while ($row = $result->fetch_row()) {
if ($row['UserID'] == $UserID) {
echo "Friend ID: " . $row['FriendID'];
} else {
echo "User ID: " . $row['UserID'];
}
}
答案 1 :(得分:0)
使用此逻辑
while($row = $result->fetch_row()) {
if($row['UserID'] == $UserID)
{
echo $row['FriendID'];
} else {
echo $row['UserID'];
}
}
答案 2 :(得分:0)
只需UNION
双方,进行查询:
SELECT FriendId
FROM Friends
WHERE UserId = @UserId
UNION ALL
SELECT UserId AS FriendId
FROM Friends
WHERE FriendId = @UserId
这将返回@UserId
的所有朋友以及@UserId
成为其朋友的所有用户的一个简单列表。