什么是错误的语法在我的mysql选择语句(php, mysql)


Whats wrong with the syntax in my mysql select statement (php, mysql)

我有一个表,我试图提取一个名为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

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

编辑:

好的,试试这个:

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

你得到了什么?

第一个获取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添加到查询中,并检查是否有行

您已经重命名了MAX(order_num) AS order_num,因此您应该尝试使用order_num仅作为echo $result_array['order_num']获取值

和while中,你应该通过在while循环

中放置下面的代码来检查你是否获得了值
echo '<PRE>';
print_r($row);
echo '</PRE>';

这可能会帮助你…,

<?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.
}