PHP逻辑问题
我有一个 sql 表 images
,其中包含列 id
、imagePath
、caption``count
。
要查看这些图像,我所做的是,我要求提供页码并查询 iamge
$limit=$page-1;
$sel=$mysqli->prepare("SELECT id,imagePath,caption,count from images".
" order by id desc limit ".$limit.",1");
这会正确显示图像。
但我有另一个函数,它显示数据库中所有图像中的 4 个随机缩略图。对于这些图像,我还提供了一个 href 标签,以便当用户单击该链接时,他将被带到该图像的页面。
现在问题出在这些链接上。 假设我在数据库中有这样的图像
id=1
id=2
id=3
id=4
id=5
要找到特定ID的页码我所做的是
$newid=$idOfTheCurrentImage-($idOfTheLastImage-1);
使用这个逻辑我得到
id=1 page=5
id=2 page=4
id=3 page=3
id=4 page=2
id=5 page=1
如果所有ID都按顺序,这会给出正确的结果。但如果任何一个 id 被删除,这个逻辑就会失败。
还有其他解决办法吗?
I have a sql table images
which has columns id
,imagePath
,caption``count
.
To view those images what i do is, I ask for the page number and query the iamge
$limit=$page-1;
$sel=$mysqli->prepare("SELECT id,imagePath,caption,count from images".
" order by id desc limit ".$limit.",1");
This shows images correctly.
But i have another function which shows 4 random thumbnail of that images out of the total images from the database.With those images i also give a href tag so that when a user clicks on that link he is taken to the page of that image.
Now the problem is with those links.
Suppose i have images like these in the database
id=1
id=2
id=3
id=4
id=5
To find the page number of the specific id what i do is
$newid=$idOfTheCurrentImage-($idOfTheLastImage-1);
Using this logic i get
id=1 page=5
id=2 page=4
id=3 page=3
id=4 page=2
id=5 page=1
This gives correct results if all the ids are in order. But if anyone of the id is deleted this logic fails.
Is there any other solution?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以执行以下操作:
添加另一个字段,即“序列号”,这样您就有了对 ($id, $seq_number),并像使用 $seq_number 一样进行计算。不要忘记在删除时更新序列号字段。
获取数组中的所有 id,并在那里进行计算。在此选项中,计算中不使用 $id 值,您仅使用数组索引。
希望这有帮助。干杯
You could do the following:
Adding another field, a 'sequential number' , so you have pairs ($id, $seq_number), and do your calculations as you did with $seq_number. Don't forget to update the sequential number field it on delete.
Get all the id's on an array, and calculate over there. In this option, the $id value is not used in the calculations, you use only the array indexes.
Hope this helps. Cheers
我建议使用除运行计数器之外的其他东西作为页面分母。正如你所说,它可能会发生变化,或者如果中间缺少一个数字就会失败。
您的图像有标题。您可以从中创建一个“slug”并将其用作页面分母。
创建链接时不再有古怪的数学或模糊的逻辑,也不再有消失的页面。
I would suggest using something other than a running counter as the page-denominator. As you say, it is subject to change, or fail if a number is missing in between.
Your images have a caption. You could create a "slug" from that and use that as your page-denominator.
No more quirky maths or murky logic when creating links, no more disappearing pages.