此查询的目的是从同一张表中检索真实图像和3张随机生成的图像,然后随机显示它们.用户(孩子)必须选择正确的图像.
Purpose of this query is to retrieve a true image plus 3 random generated images from same table, then show them randomly. User(child) have to select correct image.
谢谢
$sql= "SELECT * FROM `login` WHERE `user` = '$word'"; " UNION" "SELECT * FROM `login` WHERE `user` != '$word' ORDER BY RAND() LIMIT 3"; $row2=mysql_query($sql); $i=1; while ($r = mysql_fetch_array($row2)) { echo '<td> '; echo '<img src="sigg/'.$r['img'].'" width="130" height="130" /><br>'; echo $r['user']; echo '</td>'; $i++; }推荐答案
使用 UNION 子句:
$sql = "(SELECT * FROM `login` WHERE `user` = '$word')"; $sql.= " UNION"; $sql.= " (SELECT * FROM `login` WHERE `user` != '$word' ORDER BY RAND() LIMIT 3)"; $sql.= " ORDER BY RAND()";要获取结果,您可以使用例如 MySQLi (在OP添加具有mysql_*函数的代码之前发生):
To get the results you can use for example MySQLi (poseted before OP added his code with mysql_* functions):
$MySQL=new mysqli("localhost", "username", "password", "database"); $query = $MySQL -> query($sql); while ($entry = $query -> fetch_row()) { // $entry is an array with the results, use for example: echo $entry[0]; // will return the first column of your table echo $entry[1]; // will return the second column of your table // try also: var_dump($entry); // outputs everything for testing purposes }请不要使用 mysql_* 函数,它们已已弃用,并将在以后的PHP版本中将其删除.使用 MySQLi 或 PDO ..请参见为什么不应该在PHP中使用mysql_ *函数?以获取更多详细信息.
Please, don't use the mysql_* functions, they are deprecated and will be removed in the future versions of PHP. Use MySQLi or PDO instead. See Why shouldn't I use mysql_* functions in PHP? for more details.