mysqli获取记录

时间:2012-12-25 00:23:34

标签: php mysql mysqli mysqlimport picturegallery

这是关于Show three images from each user的帖子,其中有一个很好的解决方案可以解决我遇到的同样问题。

if ($stmt = $mysqli->prepare("SELECT p1.userID, p1.picture as pic1, p2.picture as pic2, p3.picture as pic3
FROM
  pictures p1 left join pictures p2
  on p1.userID=p2.userID and p1.picture<>p2.picture
  left join pictures p3
  on p1.userID=p3.userID and p1.picture<>p3.picture and p2.picture<>p3.picture
GROUP BY p1.userID
LIMIT ?,1")) {

    $stmt->bind_param("i", $first); 
    $stmt->execute();
    $stmt->bind_result($user, $pic1, $pic2, $pic3);
    $stmt->fetch();
    $stmt->close();
}
$mysqli->close();
?>
<div style="position:absolute; top:50px; left:100px; width:800px; text-align: center;">
  <img src="<?PHP echo (isset($pic1) ? $image_path.$pic1 : $no_image); ?>" width="176px" height="197px">
  <img src="<?PHP echo (isset($pic2) ? $image_path.$pic2 : $no_image); ?>" width="176px" height="197px">
  <img src="<?PHP echo (isset($pic3) ? $image_path.$pic3 : $no_image); ?>" width="176px" height="197px">
</div>

我想知道如何在此查询中获取pictureID?例如,如果我使用图片进行投票,那么我也必须获得pictureID。

在Supericy帮助之后回答:(如果有人在寻找相同的内容)

if ($stmt = $mysqli->prepare("SELECT p1.userID, p1.picture as pic1, p1.pictureID as pic1id, p2.picture as pic2, p2.pictureID as pic2id, p3.picture as pic3, p3.pictureID as pic3id
FROM
  pictures p1 left join pictures p2
  on p1.userID=p2.userID and p1.picture<>p2.picture
  left join pictures p3
  on p1.userID=p3.userID and p1.picture<>p3.picture and p2.picture<>p3.picture
GROUP BY p1.userID
LIMIT ?,1")) {

然后绑定它

$stmt->bind_result($user, $pic1, $pic1id, $pic2, $pic2id, $pic3, $pic3id);

2 个答案:

答案 0 :(得分:1)

试试这个,

SELECT p1.userID,coalesce(p1.pictureID,p2.pictureID,p3.pictureID) pictureID, 
       coalesce(p1.picture,p2.picture,p3.picture) as pic
FROM
  pictures p1 left join pictures p2
  on p1.userID=p2.userID and p1.picture<>p2.picture
  left join pictures p3
  on p1.userID=p3.userID and p1.picture<>p3.picture and p2.picture<>p3.picture
GROUP BY p1.userID,pictureID,pic
LIMIT ?,1

答案 1 :(得分:1)

假设图片的ID列名为“pictureID”:

SELECT p1.userID, p1.picture as pic1, p1.pictureID as pic1id, p2.picture as pic2, p2.pictureID as pic2id, p3.picture as pic3, p3.pictureID as pic3id
FROM
  pictures p1 left join pictures p2
  on p1.userID=p2.userID and p1.picture<>p2.picture
  left join pictures p3
  on p1.userID=p3.userID and p1.picture<>p3.picture and p2.picture<>p3.picture
GROUP BY p1.userID
LIMIT ?,1

然后绑定结果时:

$stmt->bind_result($user, $pic1, $pic1id, $pic2, $pic2id, $pic3, $pic3id);