获取显示的最后一条记录的ID(未插入)

时间:2015-11-03 15:51:47

标签: php mysql

这是一个显示数据库中三列记录的代码,这里我想要捕获列中显示的最后一条记录的id(不要将它作为数据库中的最后一条记录)我只是意味着列中显示的最后一项内容

$i = 1;

$sql = "select * from customers ORDER by customers_name limit 10";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);

echo "<table>";

while ($row = mysql_fetch_array($result)) {
if ($i == 1) {
 echo "<tr>";
}
echo "<td><a href=\"customers.php?cust_id=" . $row['cust_id'] . "\">$row[cust_name]</a></td>";
if ($i == 3) {
 $i = 1;
 echo "</tr>";
}
else {
 $i++;
}
}

echo "</table>";

2 个答案:

答案 0 :(得分:2)

while ($row = mysql_fetch_array($result)) {
   $last_row = $row;
   ...
}
echo 'Last ID'.$last_row['id']; //or 'cust_id'
//or
echo 'Last row:'.json_encode($last_row);

答案 1 :(得分:0)

我可能会再次误解,但我认为你希望在每个列中找到最后一个ID而不是最后一个ID,无论哪个恰好是最终占用/填充的表格单元格?如果是这种情况,那么也许下面的逻辑可能有助于解决你的难题。

/* a counter and an array to store last id in each column */
$i=0; $last=array( 'column_1'=>0, 'column_2'=>0, 'column_3'=>0 );

$tbl=array();
$tbl[]="<table border=1 cellpadding='5px'>";


/* This uses my db connection and query method so you would need to use yours instead */
while( $rs=$stmt->fetch( PDO::FETCH_OBJ ) ){

    $id=$rs->id;
    $customer=$rs->cust_name;

    if( $i==0 ) {
        $tbl[]='<tr>';

    } elseif( $i > 0 && $i % 4==0 ) {
        $tbl[]='</tr>';         
        $i=0;
    }
    else {
        $tbl[]="<td id='c_{$id}'><a href='/customers.php?cust_id={$id}'>{$customer}</a></td>";

        if( $i % 1==0 && $i % 2!=0 && $i % 3!=0 ) $last['column_1']=$id;
        if( $i % 2==0 ) $last['column_2']=$id;
        if( $i % 3==0 ) $last['column_3']=$id;
    }
    $i++;
}
$tbl[]='</table>';

echo implode( PHP_EOL, $tbl );
echo '<pre>',print_r($last,true),'</pre>';
相关问题