Load next ID or restart at the first [duplicate] - php

This question already has answers here:
Auto Increment after delete in MySQL
(18 answers)
Closed 7 years ago.
I need to display the next id from a table but if there isn't a next id, I'll display the first id of the table.
Despite a lot of tries, I was just able to display next id if next id follow +1 like my sample
Can you help me to custom my script ? Thank you very much for helping
<?php // verify that id+1 exist
$verif_page_next = $planning_id +1;
$req = mysql_query("SELECT id FROM planning WHERE id = '" . $verif_page_next . "'")
or exit(mysql_error());
if (mysql_num_rows($req) == 1) {
$next_page = $verif_page_next ;
}
// we start the first id
else {
$next_page = 1 ;
}
?>
So, if I delete an ID (e.g the ID 3), it restart to the first ID, and I wish to jump to the ID n° 4

You can select all ids bigger than the active one and only return the smallest of them. This way you get the next one.
SELECT id FROM planning WHERE id > :id ORDER BY id LIMIT 1
with binding :id to $planning_id

Related

how to get the NEXT AVAILABLE row / ID in a database as opposed to the LAST? [duplicate]

This question already has answers here:
Make auto increment fill previously deleted number [duplicate]
(3 answers)
Closed 2 years ago.
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.
First of all it should be stated, that it's better to just let the auto increment do its job, and leave the gaps there. But, if you insist on filling up every possible gap in the id-s, then this is how you could approach it:
SELECT (CASE WHEN `wpm`.`min_id` = 1 THEN MIN(`u`.`id` + 1) ELSE 1 END) as next_id
FROM `wp_posts` wp
LEFT JOIN `wp_posts` wp2 ON `wp2`.`id` = `wp`.`id`+1
LEFT JOIN (SELECT MIN(id) as `min_id` FROM `wp_posts`) as wpm ON 1
WHERE `wp2`.`id` IS NULL
This will pair up id-s with their subsequent id-s, and return the minimum of those that do not have a subsequent id on the table. Because of the nature of this, 1 being a missing id is a special case, so we have to account for that as well.
Maybe you can use this
select auto_increment from information_schema.TABLES
where TABLE_NAME ='tablename' and TABLE_SCHEMA='database_name';
and if you don't want to use information_schema then you can use
SHOW TABLE STATUS LIKE 'table_name'

Delete maxdate From table without ID [duplicate]

This question already has answers here:
Deleting a row based on the max value
(4 answers)
Closed 5 years ago.
I want to Delete a row with the highest date, but the table I am working with doesn't have auto increment ID's instead it has multiple rows with the same ID, but each row has different information.
I want to DELETE the highest date, because that is also the last date that is inserted with that ID so that is why I want to use MAX, otherwise I am deleteing all the rows with that ID.
Right now I am trying (This is my query from my PHP file):
DELETE FROM onderhoudsLog
WHERE systeemContractID = :systeemContractID
AND startDatum = MAX(:startDatum)
The DELETE does not work.
This is my PHP function:
function onderhoud($id, $startDatum){
$query = "DELETE FROM onderhoudsLog WHERE systeemContractID = :id AND startDatum = MAX(:startDatum");
$q = $this->DB->prepare($query);
$q->execute(Array(
':id' => $id,
':startDatum' => $startDatum,
));
}
Order the data by date and delete only the first record
DELETE FROM onderhoudsLog
WHERE systeemContractID = :systeemContractID
ORDER BY startDatum DESC
LIMIT 1

How can I select the latest entry of mySQL database table? [duplicate]

This question already has answers here:
MySQL Select By Newest Timestamp
(4 answers)
Closed 6 years ago.
I select the latest inserted id from my mySQL database. I also want to select the appropriate name to that latest id.
$pdo = $db->query('SELECT *,MAX(id) AS latest FROM data');
while ($row = $pdo->fetch(PDO::FETCH_ASSOC)) {
$id = $row["latest"];
$name = $row["name"];
}
The selecting of the id is working well. But not the latest name is selected, instead always the name of the first row of my table is selected. It doesn't fit to the id
Why not just
SELECT name, id FROM data ORDER BY id DESC LIMIT 1
I wanted to write following answer but i have to confess that i find e4c5's answer better.
SELECT * FROM data where id = (SELECT max(id) FROM data)

Select user id with a minimum value SQL [duplicate]

This question already has answers here:
SQL select only rows with max value on a column [duplicate]
(27 answers)
Closed 7 years ago.
How do I select from a database table a user id that is linked to the minimum value of the table
for example
User ID Pending
------- --------
0 5
1 4
2 7
'$resultSet = $mysqli->query("SELECT MIN(write_pending) FROM writerdata_tb");
if ($temp = $resultSet->fetch_assoc()) {
}'
in this case, I would want the data that is returned to have the value of the user with the least pending, in this case being user 1. How do I set up a MySqli query to handle this? And what would be the best way to save the result as a variable for use in the rest of my php?
Probably something like this, but it depends heavily on what your table structure is like. I've assumed you've got a generic users table with some IDs and this pending value you've mentioned.
SELECT userID FROM users WHERE pending = ( SELECT MIN(pending) FROM users );
The nested Select statement gets the smallest pending value in that column of your table, then you can refine your select userID statement by forcing pending to be the value returned from that nested select call.
UPDATE
To clarify your followup question of processing results, here's a modification of the code you provided:
$resultSet = $mysqli->query("SELECT userID FROM users WHERE pending = ( SELECT MIN(pending) FROM users )");
if($resultSet->num_rows > 0) {
//We use a while loop here, in the event that there are multiple rows
while($row = $resultSet->fetch_assoc()) {
echo $row["userID"]; //Accessing the rows index at "userID"
}
}

show row only 100 times PHP

How can I make a limit of showing the results? I need to limit it for 100 views.
In DB I have:
ID|NAME|PAGE|COUNT|DATE
In count I want to count untill 100 and then stop showing that ID. I could do it with count < 100. And then update the specific ID. I could get records with less than 100 views, but I couldn't manage to update count on the specific ID.
Row is showed with:
php code:
foreach($bannerGroups[0] as $ban) {
echo '<li class="right1">'.$ban->html().'</li>';
}
But I just don't know where to put the update in there. I tried, but all I got was to update only one ID. But it shows 4 on one page and randomizes them on refresh. So I don't know what to do.
Also I would like to say I am only learning php. Sorry for all the mess.
Code at http://pastebin.com/A9hJTPLE
If I understand correctly, you want to show all banners that have been previously-displayed less than 100 times?
If that's right, you can just add that to your WHERE clause:
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' WHERE `COUNT` < 100");
To update them all, you can either run a query while displaying each individual banner, or "record" the id of each and run a single query at the end, like:
$ids = array();
foreach($bannerGroups[0] as $ban) {
$ids[] = $ban['ID']; // record the ID; don't know how Banner
// class works, assuming uses indexes; maybe ID() method?
echo '<li class="right1">'.$ban->html().'</li>';
}
...
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
UPDATE:
Based off of a comment, your Banner class doesn't have a method to retrieve the individual banner's ID. In this case, you can record the ID values when you're building your banners array:
$ids = array();
while($row=mysql_fetch_assoc($bannerResult)) {
$banners[] = new Banner($row);
$ids[] = $row['ID']; // record the ID
}
// update the `count` on each record:
mysql_query('UPDATE table SET `COUNT` = `COUNT` + 1 WHERE ID IN (' . join(',', $ids) . ')');
sorry, but I got your question wrong...
first you have to insert a new sql-column like "viewcount" to the db...
on every read, you have to increment the value in viewcount...
for that behaviour (because, mysql does not allow sub-selects on update-clause on the same table), you have to fetch the results from db, as you do that, and pass all the primary-keys of the records to an array...
after the view-logic you have to fire up a query like:
UPDATE foo SET viewcount = viewcount + 1 WHERE id IN (1,2,3,4,5,6...,100);
where the IN-clause can be easily generated using your primary-keys-array with "implode(',', $arr);"
hope this helps.
$bannerResult = mysql_query("SELECT * FROM table WHERE page='cat' AND `count`<100");
#newfurniturey figured it out. in each foreach($banneruGroups added: $ids = $ban->getValue('id'); and then mysql_query("UPDATE dataa SET COUNT = COUNT + 1 WHERE id = '$ids'"); but is there any way to update them by adding query only once? And if the id is showed already 100 times i get Warning: Invalid argument supplied for foreach() in. Any idea how to fix it? I have 4 ids in DB . If one of them already have 100 views (count) then i get error!
Try to limit your data source for 100 items.
It's like OFFSET x LIMIT 100 in MySQL/PostgreSQL query or TOP 100 in MSSQL.

Categories