0

我有一个表,我正在尝试提取名为 order_num 的列的最大值,该列有 33 个整数,从 1 到 33。我希望在这种情况下将值“33”作为其最高数字。

$userid 是一个从单行表派生的整数,其中包含我要检索的字段 id

//get the currentUser ID so we know whos deck to ammend
$userIDSQL = "SELECT id FROM currentUser";
$userIdResult = mysqli_query($db, $userIDSQL) or die("SQL Error on fetching user ID: " . mysqli_error($db));

$result_array = array();
while ($row = mysqli_fetch_assoc($userIdResult)) {
    $result_array[] = $row['id'];
}

//the actual user id
$userId = $row['id'];
echo "user id is " . $userId;

在 $userId 上执行 print_r 显示数组为空,这就是下面的代码不起作用的原因.. :(

...

$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));

        $result_array = array();
        while ($row = mysqli_fetch_array($reOrderDeckResult)) {
            $result_array[] = $row['MAX(order_num)'];
            echo "the result is" . $result_array['order_num'];
            echo "the result is" . $row['order_num'];
            echo "the result is" . $result_array['MAX(order_num)']; //tried different methods to get the output.
        }

我得到的输出是

the result is  the result is  the result is

有谁知道为什么我不能从表格中得到结果?

4

4 回答 4

2

编辑:

好的,试试这个:

while ($row = mysqli_fetch_array($reOrderDeckResult)) {
   print_r($row);
}

你得到了什么?

于 2013-06-14T13:53:42.153 回答
1

由于您使用了数组,您获取 userId 的第一个代码不起作用,请更改为:

$userId = 0;
while ($row = mysqli_fetch_assoc($userIdResult)) {
    $userId = $row['id'];
}

正如我在下面显示的,如果您只期望一行,则删除 while 循环并只调用fetch_assoc一次。

鉴于您只想要单行,您不需要 while 循环:

$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId' LIMIT 1";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));

if($reOrderDeckResult && mysqli_num_rows($reOrderDeckResult) == 1)
{
    $row = mysqli_fetch_assoc($reOrderDeckResult);
    echo 'result: ' . $row['order_num'];
}
else
{
    echo 'No rows found!!';
}

我还添加LIMIT 1到查询中,并检查是否有任何行。

于 2013-06-14T14:05:03.793 回答
0

这可能会帮助你..,

<?php

$reOrderDeckSQL = "SELECT MAX(order_num) AS order_num FROM decks WHERE id='$userId'";
$reOrderDeckResult = mysqli_query($db, $reOrderDeckSQL) or die("SQL Error on reOrder: " . mysqli_error($db));

$result_array = array();
while ($row = mysqli_fetch_array($reOrderDeckResult)) {

   //you have to use the alias name not aggregate function title
    $result_array[] = $row['order_num'];

    echo "the result is" . $result_array['order_num'];
    echo "the result is" . $row['order_num'];

    //you have to use the alias name not aggregate function title
    echo "the result is" . $result_array['order_num']; //tried different methods to get the output.
}
于 2013-06-14T13:58:32.877 回答
0

您已重命名您的MAX(order_num) AS order_num,因此您应该尝试 order_num仅使用 as来获得价值echo $result_array['order_num']

在while中,您应该通过将以下代码放在while循环中来检查您是否获得了价值

echo '<PRE>';
print_r($row);
echo '</PRE>';
于 2013-06-14T14:05:03.227 回答