所以我在phpmyadmin和我的php代码中运行相同的查询。
查询是:
SELECT comments.roomID,comments.message, comments.dateTimeSent, sender.fname ,sender.lname,receiver.fname, receiver.lname
FROM comments
INNER JOIN users as sender ON comments.senderID = sender.id
INNER JOIN users as receiver ON comments.receiverID = receiver.id
INNER JOIN chatRooms ON comments.roomID = chatRooms.id WHERE comments.roomID = 8;
当我直接从phpmyadmin面板运行时,我得到的结果就是这个
但是当我在我的PHP代码中运行时,我得到了这个结果:
Array
(
[roomID] => 8
[message] => Hello from mysql database
[dateTimeSent] => 2018-03-16 11:04:03
[id] => 23
[fname] => pavlos
[lname] => elpidorou
)
Array
(
[roomID] => 8
[message] => asdasd;asda
[dateTimeSent] => 2018-03-16 11:21:30
[id] => 25
[fname] => Antreas
[lname] => antoniou
)
数组中缺少sender.fname
,sender.lname
,receiver.fname
,receiver.lname
我用来执行查询的代码,得到的结果如下
foreach ($chatRoomArray as &$room) {
$roomID = $room['id'];
$query = "SELECT comments.roomID,comments.message, comments.dateTimeSent,sender.id, sender.fname ,sender.lname,receiver.fname, receiver.lname
FROM comments
INNER JOIN users as sender ON comments.senderID = sender.id
INNER JOIN users as receiver ON comments.receiverID = receiver.id
INNER JOIN chatRooms ON comments.roomID = chatRooms.id WHERE comments.roomID = ".$roomID;
$stmt = $this->conn->prepare($query);
$result = $stmt->execute();
$commentArray = array();
if ($result) {
$num = $stmt->rowCount();
if ($num > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row);
print_r($row);
$comment = array(
"commentID" => $row['id'],
"message"=>$row['message'],
"dateTimeSent"=>$row['dateTimeSent'],
"senderFname"=>$row['sender.fname'],
"senderLname" => $row['sender.lname'],
"receiverFname" => $row['receiver.fname'],
"receiverLname" => $row['receiver.lname']
);
}
}
}
}
答案 0 :(得分:2)
PHP + MySQL不会在字段名称中包含表名。
当您运行查询时,请在SELECT
部分为其命名。
SELECT `sender`.`fname` AS `sender_fname`, ...
然后它将作为sender_fname
位于您的数组中。我会避免在你的名字中使用圆点。
答案 1 :(得分:2)
您必须添加唯一的别名
sender.fname, sender.lname, receiver.fname,receiver.lname
例如:
SELECT comments.roomID,comments.message, comments.dateTimeSent, sender.fname as 'fname1' ,sender.lname as'lname1',receiver.fname as 'fname2', receiver.lname as 'lname2'
FROM comments
INNER JOIN users as sender ON comments.senderID = sender.id
INNER JOIN users as receiver ON comments.receiverID = receiver.id
INNER JOIN chatRooms ON comments.roomID = chatRooms.id WHERE comments.roomID = 8;
然后进入php
"senderFname"=>$row['fname1'],
"senderLname" => $row['lname1'],
"receiverFname" => $row['fname2'],
"receiverLname" => $row['lname2']