使用jQuery和mysqli_num_rows()获取错误的数组长度

时间:2016-09-10 06:16:42

标签: javascript php jquery

我使用jQuery将新数据添加到数据库表。然后我从该表中获取所有内容。问题是我每隔一段时间就会得到错误的数组大小。如果我刷新页面它的数组大小正确,但是当我点击带有jQuery功能的按钮时,它就搞砸了。

我弄明白了

 $n = mysqli_num_rows($result);

已经返回了错误的行数

这是脚本:

$(document).ready(function(){

    $.getallentries = function(){
        $.getJSON("entries.php",{action : "getall"},function(data) {
            var content_array = $.map(data, function(e) { return e;});   
            console.log(content_array.length); // to check array size
        });

        $.addstatic = function(){
            $.post("entries.php",{action : "addstatic"});
        };

    };

    $("#adds").on("click",function(){
        $.addstatic();  
        $.getallentries();
    });

    $.getallentries();

这是entries.php:

function getall(){

    $link = db_connect(); 
    $query= "SELECT * FROM jq";

    $result = mysqli_query($link,$query, MYSQLI_STORE_RESULT);// Smart people said MYSQLI_STORE_RESULT should help but it didn't

    $n = mysqli_num_rows($result);

    for($i = 0 ;$i<$n;$i++)
        {
            $row=mysqli_fetch_assoc($result);

            $b[]=$row;
        }


    echo json_encode(array($b));  

}

function addstatic(){
    $link = db_connect(); 
    $statin_Entry = "Static Entry";
    $query = "INSERT INTO jq (Entry) VALUES ('$statin_Entry')";
    $result = mysqli_query($link,$query);

}   

if(isset($_GET['action']) && !empty($_GET['action'])) {
    $action = $_GET['action'];
    switch($action) {
    case 'getall' : getall(); break;
    }
}
else {
    if(isset($_POST['action']) && !empty($_POST['action'])) {
        $action = $_POST['action'];
        switch($action) {
        case 'addstatic' : addstatic();break;
        case 'removelast' : removelast();break;
            // ...etc...
        }
    }
}

这是数组长度的日志 This is log of array length

所以问题再次出现,相同的数组大小为143,146,151,其中156 =

1 个答案:

答案 0 :(得分:0)

您应该在$.getallentries AJAX调用的回调函数中调用$.addstatic,以便它在$.addstatic完成数据库更新后运行。

    $.addstatic = function(){
        $.post("entries.php",{action : "addstatic"}, $.getallentries);
    };

在获取行之前无需使用mysqli_num_rows。你应该使用这样的循环:

while ($row = mysqli_fetch_assoc($result)) {
    $b[] = $row;
}

此外,您将数组包装在另一个数组中。只是做:

echo json_encode($b);

您编写的方式,console.log(content_array.length)应始终记录1,我不了解您是如何获得更高的数字。您确定发布了实际代码吗?

没有使用点$.map,它所做的只是制作data数组的副本。只需使用data本身。

在PHP中,您不需要同时测试isset()!empty(),因为empty()会检查变量是否先设置。

您不需要使用MYSQLI_STORE_RESULT,它是该选项的默认设置。

相关问题