I have an image folder and in it, there are nearly 200 images. My image names are :

我有一个图像文件夹,其中有近200张图像。我的图片名称是:

101.png
102.png
103.png
(it continues until 300.png)

These images are the images which my books have in mysql database. For example;

这些图像是我的书在mysql数据库中的图像。例如;

id | book_name
101| aaaaa
102| bbbbb

So, I want to change my image names as book names. That is to say, the image name of "aaaa" book will be aaaa.png instead of 101.png. Is there any quick way to do this? Thanks....

所以,我想将我的图像名称更改为书名。也就是说,“aaaa”书的图像名称将是aaaa.png而不是101.png。有没有快速的方法来做到这一点?谢谢....

3 个解决方案

#1


2

Here is a simple example:

这是一个简单的例子:

$db = new PDO('mysql:host=myhost;dbname=mydb', 'myuser', 'mypass');
$books = $db->query('SELECT * FROM books');
$images_folder = '/var/bookimages/';

foreach ($books as $book) {
    $old_image_file = realpath($images_folder.$book['id'].'.jpg');
    if ($old_image_file) {
        $clean_book_name = filter_var($book['book_name'], FILTER_SANITIZE_ENCODED);
        $new_image_file = realpath($images_folder).$clean_book_name.'.jpg';
        rename($old_image_file, $new_image_file);
    }
}
  • PDO handles interactions with the database. It's the preferred way of connecting to databases on PHP.
  • PDO处理与数据库的交互。它是连接PHP上数据库的首选方式。
  • The rename() function only works if the origin and destination names are files in the same disk. On your case, this should work fine.
  • rename()函数仅在原始名称和目标名称是同一磁盘中的文件时才有效。在你的情况下,这应该工作正常。
  • I've used a very simple query on the database. Usually, you'll want to limit it and specify the columns you want.
  • 我在数据库上使用了一个非常简单的查询。通常,您需要限制它并指定所需的列。
  • I'm using filter_var to check if the name in the database is valid. This is a security measure. If the database has a file name containing '../' the file won't do bad things. This is necessary because rename() can also move files and someone may exploit it.
  • 我正在使用filter_var来检查数据库中的名称是否有效。这是一项安全措施。如果数据库的文件名包含“../”,则该文件不会做坏事。这是必要的,因为rename()也可以移动文件,有人可能会利用它。

更多相关文章

  1. 视差滚动与图像仅通过徽标透明度
  2. 具有固定宽度网格的引导程序和应跨越窗口宽度的图像
  3. 从文本框值生成条形码图像
  4. Div高度为图像高度,图像宽度为div宽度
  5. 如何将图像(PNG)转换为2D数组(二进制图像)?
  6. 使用CSS,HTML和Javascript在随机图像的页面上进行图像大小调整
  7. 在图像映射中的背景图像
  8. 动画在画布中移动图像
  9. Nivoslider(在动态ajax内容中)不会在第一次加载时加载图像

随机推荐

  1. Android启动流程
  2. [android]实现拖动效果
  3. Android screenOrientation 屏幕方向的设
  4. Android(安卓)4.0.3 联系人(通讯录)应用
  5. Android实用小技巧
  6. Android View MarqueeView 跑马灯效果
  7. 关于Android使用新浪API的一些说明
  8. Android高德地图自定义放大缩小控件
  9. 在android中使用OrmLite数据库框架
  10. Android map