php - How can I make sure that two rows selected at random are different from one another? -


i have table photos many photos in , need select 2 @ random:

in getnew.php

$result = mysqli_query($conn,"select * photos order rand() limit 1"); $result2 = mysqli_query($conn,"select * photos order rand() limit 1");    $row = $result->fetch_assoc();   $img1link = $row['link'];   // more stuff $row    $row2 = $result2->fetch_assoc();   $img2link = $row2['link'];   // more stuff $row2 

however need prevent selecting same photo twice (the selected photos must different), i.e. $img1link should not = $img2link. need retrieve data using $.getjson in file, using array @ end of getnew.php.

the array @ end of getnew.php:

echo json_encode(array('img1'=>$img1link,'img2'=>$img2link, ...(etc)... )); 

how can make sure selected photos different time variable stored in array? tried create if/else statement didn't understand doing.

you can execute once 2 instead you'll never pick same row:

$result = mysqli_query($conn,"select * photos order rand() limit 2"); $row = $result->fetch_assoc(); $row2 = $result->fetch_assoc(); // invoke `->fetch` twice first , second row $img1link = $row['link']; $img2link = $row2['link']; 

sidenote: careful of order rand() clause since it'll slow on large data sets. can use alternative @bill karwin's great answer


Comments