简体   繁体   中英

Select query slow to update

This is probably a simple error, but I'm stumped...

I have a database that has entries inserted using AJAX on a chrome extension, which works great and inserts instantly.

I have a separate PHP file that is being used to output the number of entries in a table. This works, but is takes a long time for the entries to update to the right number when called. I need it to be up to date instantly.

Is there any reason why it's taking so long for the query to output the correct number, when the table itself is updating instantly?

<?php
$link = mysqli_connect("localhost", "root", "", "fyp");

/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}
if ($result = mysqli_query($link, "SELECT * FROM links")) {

    $row_cnt = mysqli_num_rows($result);

    printf($row_cnt);

    mysqli_free_result($result);
}

/* close connection */
mysqli_close($link);
?>

Thanks.

I think you should simple run:

if ($result = mysqli_query($link, "SELECT count(*) AS `nr` FROM links")) {

    $row_cnt = mysqli_fetch_assoc($result);

    printf($row_cnt['nr']);

    mysqli_free_result($result);
}

It will be the best one. Or if your links are not removed at all you could run:

if ($result = mysqli_query($link, "SELECT id FROM links ORDER BY id DESC LIMIT 1")) {

    $row_cnt = mysqli_fetch_assoc($result);

    printf($row_cnt['id']);

    mysqli_free_result($result);
}

Hand off the processing to the database by using an aggregate query and return a scalar result with mysqli_result :

if ($result = mysqli_query($link, "SELECT COUNT(1) FROM links")) {
    $row_cnt = mysqli_result($result, 0);
    printf($row_cnt);
    mysqli_free_result($result);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM