SQL ORDER BY - 分页问题

时间:2014-05-09 22:31:19

标签: php sql mysqli

我正在尝试分页:

if ($stmt = $mysqli->prepare("SELECT CVE_ORDEN_DET, ORDEN_TRABAJO_DET, NUM_MUESTRA, NUM_ESPECIMEN FROM colado_det WHERE CVE_OBRA = ? ORDER BY NUM_MUESTRA LIMIT ?,  30")) {
$stmt->bind_param('ss', $obdt, $page);    
$stmt->execute();  
$stmt->store_result();
$stmt->bind_result($id,$rf, $nm, $ne);     
while ( $stmt->fetch() ) {$arr_id[] = $id; $arr_rf[] = $rf;$arr_nm[] = $nm;$arr_ne[] = $ne; }
} else {echo ("Error conectando a la base de datos"); ;}

我认为代码没问题(这只是分页的一部分),问题是在显示结果时,程序显示30行,第30行(从至少一页开始)出现在下一页(开始时)会导致丢失一条记录。

当我使用ORDER BY DESC时,问题似乎没有出现,但是使用降序不适合用户的需要,所以我需要找到导致这个问题的原因,以及如何解决它。

我认为问题在于sql,而不是PHP,有人可以帮我确认一下,或者给我一个暗示可能导致这种情况的原因吗?请!

欢迎提供一些文档。提前谢谢。

修改

分页的第一部分:

if ($stmt = $mysqli->prepare("SELECT COUNT(*) FROM colado_det where fecha = ?")) {
$stmt->bind_param('s', $asdfg);    
$stmt->execute();  
$stmt->store_result();
$stmt->bind_result($counting);  
$stmt->fetch();    
    $all = $counting;
    $page = round($page, 0);
    $page = (30)*($page); 
    $counting = $counting / 30;
    $counting = ceil($counting);
    if($counting<1){$counting=1;}
} else {echo ("Error conectando a la base de datos");}

页面变量通过$ _GET收到一个数字;它是一个后来乘以[要显示的记录数]的数字,以便从中获取记录号。

我测试了它,并且在使用ORDER BY子句时只缺少一条记录。

2 个答案:

答案 0 :(得分:0)

if ($stmt = $mysqli->prepare("SELECT COUNT(*) FROM colado_det where fecha = ?")) {
$stmt->bind_param('s', $asdfg);    
$stmt->execute();  
$stmt->store_result();
$stmt->bind_result($counting);  
$stmt->fetch();    
    $all = $counting;
    $page = round($page, 0);
    $page = (30)*($page); 
    $counting = $counting / 30;
    $counting = ceil($counting);
    if($counting<1){$counting=1;}
} else {echo ("Error conectando a la base de datos");}

我真的不确定你在这里想要完成什么,这是令人费解的。

应该是这样的;

// assuming $page is already set with the current page and you already have a variable holding $totalCount
// but I will set them here for continuity;
$page = 1;
$totalCount = 538; // this is actually unnecessary for this, but is used to set up the display and make sure you don't run the query past the last page
$startRow = (($page - 1) * 30); // page should ONLY hold the current page they're on
if ($stmt = $mysqli->prepare("SELECT CVE_ORDEN_DET, ORDEN_TRABAJO_DET, NUM_MUESTRA, NUM_ESPECIMEN FROM colado_det WHERE CVE_OBRA = ? ORDER BY NUM_MUESTRA LIMIT ?,  30")) {
$stmt->bind_param('ss', $obdt, $startRow);    
$stmt->execute();  
$stmt->store_result();
$stmt->bind_result($id,$rf, $nm, $ne);     
while ( $stmt->fetch() ) {$arr_id[] = $id; $arr_rf[] = $rf;$arr_nm[] = $nm;$arr_ne[] = $ne; }
} else {echo ("Error conectando a la base de datos"); ;}

答案 1 :(得分:0)

您正在使用LIMIT的字符串。

$stmt->bind_param('si', $obdt, $startRow);