I am uploading image files using their original name. I upload the file path etc. to a database and every image gets a unique id in the database. Until here everything works fine.
Now, I would like to give the uploaded image files their unique id from the database table as a name. (e.g. if the image id is 1, I would like the file to be called 1.jpg and so on.) I cannot get it to work.
My not working approach:
The database table
TABLE `images`
`image_id` INT(11) unsigned NOT NULL AUTO_INCREMENT,
`user_id` INT(11) unsigned NOT NULL COMMENT 'FOREIGN KEY referencing the user_id of the user, who uploaded the images',
`image_name` VARCHAR(64) NOT NULL,
`image_path` VARCHAR(64) NOT NULL,
`image_upload_timestamp` TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`image_id`);
The script to write the image to the database using its original name (working):
$database = DatabaseFactory::getFactory()->getConnection();
$sql = "INSERT INTO images VALUES ('', :user_id, :image_name, :image_path, :image_upload_timestamp)";
$query = $database->prepare($sql);
$query->execute(array(':user_id' => Session::get('user_id'),
':image_name' => $file_name,
':image_path' => $file_destination,
':image_upload_timestamp' => time()));
ImageModel::renameImage($image_id);
The renameImage method (not working!)
public static function renameImage($image_id)
{
$database = DatabaseFactory::getFactory()->getConnection();
$query = $database->prepare("SELECT * FROM images WHERE image_id = :image_id AND user_id = :user_id");
$query->execute(array(':image_id' => $image_id, ':user_id' => Session::get('user_id')));
$img_id = $query->fetch();
// Convert array to string
$file_name = $img_id->image_id;
$image_name = $file_name . '.jpg';
$sql = "UPDATE images SET image_name = :image_name WHERE :image_id = $image_id";
$sth = $database->prepare($sql);
$sth->execute(array(':image_name' => $image_name));
}
I am really new to this and would highly appreciate any kind of help! Thank you very much!