PHP未返回最新的更新的SQL过程结果

438*_*nil 4 php sql codeigniter mariadb mariasql

我正在使用mariaDB,codeigniter php

在工作台中执行该过程时,将显示正确的结果。 下图

但是,当我使用php codeigniter运行相同的过程时,它会返回不同的结果集。

array(1) {
[0]=>
array(1) {
    [0]=>
    array(2) {
        ["stuScore"]=> string(7) "44.0000"
        ["answerdQues"]=> string(2) "50"
    }
}
}
Run Code Online (Sandbox Code Playgroud)

查询过程...

SELECT sum(Score) as stuScore, count(distinct ta1.idTestQuestion) as answerdQues
            FROM (select ta0.*, @running_time := if(@running_student = idStudent, @running_time, 0) + ta0.TimeTaken, date_add(ta0.StartTime, INTERVAL @running_time SECOND) as running_time, @running_student := idStudent
                from (select tap.idStudent, ta.score, ta.idTestQuestion, tap.StartTime, ta.TimeTaken
                    from `testanswerpaper` tap
                    left join testanswer ta on ta.idTestAnswerPaper = tap.idTestAnswerPaper and (ta.Status = 'Flagged' || ta.Status = 'Answered')
                    where  tap.`idTestQuestionPaper` = TestQuestionPaperID
                    order by tap.idStudent, ta.SortOrder, ta.idTestAnswer
                ) ta0
                join (select @running_time := 0, @running_student) running
            ) ta1
            join student s on s.idStudent = ta1.idStudent
            join user u on s.idUser = u.idUser
            WHERE ta1.running_time <= now()
            group by ta1.idStudent
            order by stuScore desc, answerdQues DESC;
Run Code Online (Sandbox Code Playgroud)

php代码是

$this->readDB = $this->load->database('read', TRUE);
        $connectId = $this->readDB->conn_id ;
        $sql = "call GetLeaderBoardData($TestQuestionPaperID);";
        if (mysqli_multi_query($connectId,$sql))
        {
            do
            {
                // Store first result set
                if ($result=mysqli_store_result($connectId)) {

                        $resultArray[] = mysqli_fetch_all($result, MYSQLI_ASSOC);

                }
            } while (mysqli_next_result($connectId));

        } 
        var_dump($resultArray);
Run Code Online (Sandbox Code Playgroud)

sla*_*kso 6

The difference might come from the the fact that the user-defined variables might have different values when you execute the code from workbench vs codeigniter as the user-defined variables keep their values throughout the session.

To rule this out, reset the @running_time and @running_student values at the beginning of the procedure.

set @running_time = null;
set @running_student = null;

SELECT sum(Score)...
Run Code Online (Sandbox Code Playgroud)

  • 正如@RickJames所说,`@ running_student`未初始化。当您在代码中使用用户定义的变量(@var)时,请记住,它们在整个会话中都保持其值,并且在您调用其他例程时也可以更改。 (2认同)