I am using the following code to know where to put my next post:
// Create connection
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM `wp_posts` WHERE ID = (SELECT max(ID) FROM `wp_posts`)";
$res = $link->query($sql);
while( $rs = $res->fetch_object() ) {
echo 'Last ID is: '. $rs->ID .' <br />';
$lastID = $rs->ID;
}
// Close connection
mysqli_close($link);
$ID_of_Next_Post = $lastID + 1;
echo 'Next post will go to ID: '. $ID_of_Next_Post .' <br />';
The issue I'm facing is that if I make a post that goes into, say, ID = 100 and then I delete that post, the next time this code is called $lastID
will still equal 100 but the next post will go into 102 (because 101 was taken, even though it has been deleted and is not there anymore).
So how can I change my SQL query to find the NEXT AVAILABLE id so I know where the next post will go? The ID row is set to auto-increment so it's tempting to not set the ID of the post but I need to know what the ID is so I can set interdependencies in other tables of the database.