最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

在一个数组中合并两个MySQL查询

SEO心得admin35浏览0评论
本文介绍了在一个数组中合并两个MySQL查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此查询的目的是从同一张表中检索真实图像和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

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_*

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.

发布评论

评论列表(0)

  1. 暂无评论