0

我正在尝试链接数据库中的 2 行,以便 PHP 代码从一行中随机选择一个值,并将其链接到第二行。例子:

<?php

date_default_timezone_set("Asia/Tel_Aviv");

$mysqli = new mysqli;
$mysqli->connect("localhost", "root", "", "root");

$giftsq = $mysqli->query("SELECT * FROM `gifts`");
while($gifts = $giftsq->fetch_array())
{
    $date = date('H:i');
    if ($gifts['time'] <= $date)
    {
        $giftsid = $gifts['id'];
        // $mysqli->query("DELETE FROM `gifts` WHERE `id` = '".$giftsid."'");
        $winner = $mysqli->query("SELECT * FROM `giveaways` WHERE `giftid` = '".$giftsid."' ORDER BY RAND() LIMIT 1") or die('Error:'.$mysqli->error);
        if($winner->num_rows >= 1)
        {
            $newwinner = $winner->fetch_array;
            echo $newwinner['userid'];
        }
    }
}

?>

您可以看到它选择了所有日期小于或等于当前日期的礼物 ID。When the correct giftIDs are selected, the system want to select randomly a winner by selecting the same giftid on the second row called giveaways.

但由于某种原因它不起作用..

这是数据库的抽象:

礼物

时间是代表礼物赠品的结束时间。

id ------ title ------ img ------ creator ------ members ------ points ------ time
3         dota         1.png      Captain        250            30000         14:00
6         gta          2.png      User           303            20000         24:00
7         flolo        3.png      Captain        204            10000         22:30

赠品

id ------ giftid ------ userid
1           2           765611980448343721
2           6           765611980448343723
3           6           176561198044834371
4           6           176561198044834372
5           7           184582450892423483
6           7           423894024830294820

所有这些过程的结果是,我应该打印到屏幕上,已为gifid 编号 6 选择的用户 ID 是以下用户之一:176561198044834371 176561198044834372 176561198044834373

并且选择的giftid号7随机是以下用户之一:184582450892423483 423894024830294820

有人可以帮我理解如何做到这一点吗?

4

2 回答 2

0

尽可能多地使用 SQL 语句。可能有一种方法可以将它们组合成一个,但这只是一个简单的示例:

$time = date("H:i");

$sql = $mysqli->query("SELECT gift_id FROM gifts WHERE gift_time <= '$time'");

while($row = $sql->fetch_array())
{
    $gift = $row['g_id'];

    $g_sql = $mysqli->query("SELECT * FROM giveaways WHERE gift_id = '$gift' ORDER BY RAND() LIMIT 1");
    $g_row = $g_sql->fetch_array();

    echo '<p>' . $g_row['user_id'] . '</p>';
}
于 2013-02-08T22:08:17.677 回答
0

为什么要在 PHP 中进行过滤?这是非常低效的。为什么不简单地做

SELECT ...
FROM ...
WHERE time <= CURTIME()
于 2013-02-08T21:17:37.390 回答