drnx3715 2019-04-29 10:22
浏览 182
已采纳

从MySQL数据库获取数据后从第n行获取列数据并分配给变量

So I have fetched data from a MySQL database and I want to assign it to a variable based on an nth row. Only the bottom three rows are filtered and I want to assign values from the firs and last row to two variables.

$sql3 = "SELECT * FROM login_attempts WHERE login_attempt_user_id=? AND login_attempt_result=? ORDER BY login_attempt_id DESC LIMIT 3;";
$stmt3 = mysqli_stmt_init($conn);

if (!mysqli_stmt_prepare($stmt3, $sql3)) {
    echo 6;
    exit();

} else {

    mysqli_stmt_bind_param($stmt3, "ss", $login_attempt_user_id, $login_attempt_success);
    mysqli_stmt_execute($stmt3);
    $result2 = mysqli_stmt_get_result($stmt3);

    if (mysqli_num_rows($result2) > 0) {

        while ($row2 = mysqli_fetch_assoc($result2)) {

            $test1 = $row2['login_attempt_time'][0];

            $test2 = $row2['login_attempt_time'][2];

            echo $test1.$test2;
            exit();
        }
    } else {
        //echo 4;
        exit();
    }
}

The section of code is within the while loop and I realize that what I am attempting is for arrays. I want to do something similar to achieve my goal.

My code is not assigning the database entry to the variable: $test = $row2['login_attempt_time'] assigns the last value of the fetched row, however $test = $row2['login_attempt_time'][0] only returns the value 1.

Would anyone please be able to help with this?

  • 写回答

2条回答 默认 最新

  • douyiken0968 2019-04-29 10:38
    关注

    Fetch all (three) rows into an array (2-dimensional) with mysqli::fetch_all(). Then get the first and the last elements (rows) with reset() and end().

    Change

        while ($row2 = mysqli_fetch_assoc($result2)) {
    
            $test1 = $row2['login_attempt_time'][0];
    
            $test2 = $row2['login_attempt_time'][2];
    
            echo $test1.$test2;
            exit();
        }
    

    to

        $data = $result2->fetch_all(MYSQLI_ASSOC);
        $variable1 = reset($data); // first row
        $variable2 = end($data);   // last row
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器