简体   繁体   English

PHP数据库中的下一个ID

[英]php next id in database

I need php next id, Ex: i have this id's in database: 10, 11, 15, 19, 31,32,34 ..... 我需要php下一个ID,例如:我在数据库中有此ID:10、11、15、19、31、32、34 .....

$img_id=$_GET[img_id]; $ img_id = $ _ GET [img_id]; // to get image id from browser //从浏览器获取图片ID
$row['id']; $ row ['id']; // to get id from database //从数据库获取ID

How can I use php $i++ and check if id is set in database? 如何使用php $i++并检查是否在数据库中设置了id And ignore empty id . 并忽略空id

because i want to put next image bottom.while some images was deleted!! 因为我想把下一张图像放在底部。而有些图像被删除了!!

Thank you 谢谢

From what I understand of your question, you have rows in your database which ids are not consecutive (1, 3, 13, 16, etc), and you wish to access those rows by searching with consecutive numbers from a loop as possible ids? 据我对您的问题的理解,您数据库中的行具有不连续的ID(1、3、13、16等),并且希望通过从循环中搜索连续的ID作为可能的ID来访问这些行?

for($i=0; $i<100; $i++)
{
    $query = 'SELECT * FROM `table` WHERE `id` = ' . $i;
    $result = mysql_query($query);
    if(mysql_num_rows($result) > 0)
    {
        echo 'This id exists in the table: ' . $id . '<br />';
    }
}

100 here acts as a potential number, but it should achieve what you need. 这里100是一个潜在的数字,但它可以满足您的需求。 There's a ton of solutions that you can apply to your problem, but that would be the most straight forward I think of with the question you're asking. 您可以采用很多解决方案来解决问题,但这是我想到的最直接的解决方案。

It's quite unclear what you are trying to say. 现在还不清楚您要说什么。 But I will give it a shot. 但我会试一试。

I think what you mean is you have deleted some records from the table and it does not continue from last MAX(id) in the next insert. 我认为您的意思是您已从表中删除了一些记录,并且该记录不会从下一次插入中的最后一个MAX(id)继续。 For that you could try: 为此,您可以尝试:

As @col mentioned below, never use this in production, just your testing environment. 如下@col所述,切勿在生产环境中仅在测试环境中使用此功能。 Once a record is deleted sequence is lost. 删除记录后,序列将丢失。

mysql_query("ALTER TABLE `table_name` AUTO_INCREMENT = 1");

What this does is that if you have a table named images with the maximum id of say 99 and you deleted this image. 它的作用是,如果您有一个名为images的表,其最大id99并且您删除了该图像。 Next image you enter will have the id=100 . 您输入的下一张图片将具有id=100 So ids will now look something like 97,98,100 . 所以id现在看起来像97,98,100 This will force MySQL to continue from MAX(id) + 1 , so it looks 97,98,99 . 这将迫使MySQL从MAX(id) + 1继续运行,因此看起来为97,98,99

Also a handy function to get the last insert id from php: 还有一个方便的功能,可从php获取最后的插入ID:

$last_id = mysql_insert_id();

Now $last_id will have the last AUTO_INCREMENT value from database. 现在$last_id将具有数据库中的最后一个AUTO_INCREMENT值。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM