php - 选择 10 组查询

标签 php mysql mysqli

我点击此处的一个链接,并相应地修改了我的代码。我想要实现的目标是,例如表名 media_ids 包含 45 行(这是动态的),我想将行数划分为最少 10 行的组(在我的情况下,四组 10 行和 1 组) 5)并每小时执行每组代码。

例如,从 id 1 到 10 选择记录,然后从 11 到 20 选择第二个小时,依此类推,除非获取最后一条记录并从 id 1 重新开始。

我添加了一个跟踪器,它检查当前限制并继续。但它给了我想要实现的所需结果。

<?php
require('inc/dbConnect.php');

$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointer10=$lastPointer+10;

$currentMediaQuery = "select * from media_ids where id > ".$lastPointer." limit ".$lastPointer.",".$lastPointer10."";

$mediaQuery = mysqli_query($con, $currentMediaQuery);

if (mysqli_num_rows($mediaQuery) > 0) {
    while ($row = mysqli_fetch_assoc($mediaQuery)) {
       // do stuff…
      echo $id=$row['id']."<br>";
    }
}

else
{echo "0";}

if ($lastPointer + 10 > 40) {
    $lastPointer = 1;
} else {
    $lastPointer += 10;
}

mysqli_query($con, "update media_tracker set tracker = $lastPointer");
?>

最佳答案

我假设您每小时通过 ajax/Js 调用这个脚本... 在你的代码中,如果你从另一个脚本中删除一些数据,你可能会发现你的第一行 id 即 100 !

require('inc/dbConnect.php');

$limit = 10 ;
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];

$lastPointerRes = mysqli_fetch_assoc($lastPointerResult);
$lastPointer = empty($lastPointerRes['tracker']) ?  0 : $lastPointerRes['tracker'] ;

$lastPointer10=$lastPointer* $limit;

$currentMediaQuery = "select * from media_ids  limit ".$limit." OFFSET  ".$lastPointer10."";

$mediaQuery = mysqli_query($con, $currentMediaQuery);

if (mysqli_num_rows($mediaQuery) > 0) {
    while ($row = mysqli_fetch_assoc($mediaQuery)) {
       // do stuff…
      echo $id=$row['id']."<br>";
    }
}

else
{echo "0";}

//do a total row count query here and set  as value of $total rather than 40
$total =40 ;
$flag = ceil($total/$limit);

if ($lastPointer == $flag) {
    $lastPointer = 0;
} else {
    $lastPointer ++;
}

mysqli_query($con, "update media_tracker set tracker = $lastPointer");

关于php - 选择 10 组查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32922625/

相关文章:

php - 尝试将电子邮件的字符串表示形式从 php 存储到 MySQL

php - 将函数从MySql转换为MySqli

php - Laravel 集合 - 仅当集合包含值时才回显值

php - 如何防止 PHP 的 HTML 输出显示在浏览器中?

php - 为什么我的 PHP/MySQL 是插入而不是更新?

php - 显示所有时间约会和保留

mysql - 将日期时间分组在范围内

MySQL 错误#1111

php - MySQL POP 最后一行并将其删除

PHP:如果我在调用结果存储过程后再次使用 mysqli::query(),则“命令不同步”