user1392988
user1392988

Reputation: 3

php to rename files in directory based on columns in mysql

I was wondering if anyone could help with this. Let' say I have a db with columns 'cust_id' and 'name'. I want to rename 2000+ images in a directory to 'cust_id.jpg' from their existing 'name.jpg'. Column 'name' contains all the image names in the folder and I want them renamed to their associated customer id #.

I'm pretty certain this can be done w/ php/mysql but my knowledge of php is very limited and I wouldn't know where to start writing this. I realise I would have to create a recordset pulling the required data, read directory, loop through etc. but I this is just beyond my capabilities at the moment. Little help?

Thanks!

Upvotes: 0

Views: 2695

Answers (2)

Broncha
Broncha

Reputation: 3794

Try this code.. assuming your table name is tbl_customer and you have your db connection settings in place

$res = mysql_query("SELECT * FROM tbl_customer");

while($row = mysql_fetch_assoc($res)){
  $name = $row['name'];
  $cust_id = $row['cust_id'];

  if(file_exists('path/to/your/image/directory/'.$name)){
    rename('path/to/your/image/directory/'.$name,'path/to/your/image/directory/'.$cust_id.".jpg");
  }
}

Upvotes: 2

Imdad
Imdad

Reputation: 6042

Some details may be required for a good response. Sitll I'm giving a try to help you. I'm assuming table name etc for now. You can use your names. Also I'm assuming each customer has only one image.

UPDATE `customer_images`
SET `name` = CONCAT(`cust_id`,".jpg")

Here cust_id is the column name of customer id

Let me know if the assumptions are not correct or the SQL did not worked.

Upvotes: 0

Related Questions