bɪˈɡɪnə
bɪˈɡɪnə

Reputation: 1085

Get id of last post displayed in table

In code below I will be displaying posts in table. Now for creating load more function I need to get id of last post in table but I am not able to do that, Here $ID = $row['id']; gets me id of first post may be because it's outside loop and to get id of last post I must place this code inside loop. But where to exactly place it so that I get id of last post displayed in table.

<?php
$sql = "SELECT * FROM posts ORDER BY id desc limit 3";
$query = $db->prepare($sql);
$query->execute();
$row = $query->fetch(PDO::FETCH_ASSOC);
$ID = $row['id'];
?>

<table>
<tr>
<?php do { //horizontal looper?>
<td>
<div><h2><?php echo $row['title']; ?></h2></div>          
<div><p><?php echo $row['body']; ?></p></div>
<img src='<?php echo $row['pic']; ?>'>
<div><p><?php echo $row['about']; ?></p></div>
</td>
<?php
$row = $query->fetch(PDO::FETCH_ASSOC);
if (!isset($nested_List)) {
$nested_List= 1;
}
if (isset($row) && is_array($row) && $nested_List++%3==0) {
echo "</tr><tr>";
}
} while ($row); //end horizontal looper 
?>
</table>

Upvotes: 0

Views: 113

Answers (2)

Darshan Dave
Darshan Dave

Reputation: 645

Try This Query

<?php 
 try { 
 $dbh = new PDO('mysql:host=localhost;dbname=test', 'username', 'password'); 

 $stmt = $dbh->prepare("INSERT INTO test (name, email) VALUES(?,?)"); 

  try { 
    $dbh->beginTransaction(); 
    $tmt->execute( array('user', '[email protected]')); 
    $dbh->commit(); 
    print $dbh->lastInsertId(); 
  } catch(PDOExecption $e) { 
    $dbh->rollback(); 
    print "Error!: " . $e->getMessage() . "</br>"; 
} 
 } catch( PDOExecption $e ) { 
   print "Error!: " . $e->getMessage() . "</br>"; 
 } 
?> 

Upvotes: 0

Abhishek Sharma
Abhishek Sharma

Reputation: 6661

Try this code :-

    $ID1 = $row[0]['id'];//first id of table
    $ID2 = $row[1]['id'];//2 id of table
    $ID3 = $row[2]['id'];//3 id of table

get latest id:-

$sql = "SELECT * FROM posts ORDER BY id desc limit 1";

Upvotes: 1

Related Questions