Zoung Zoung - 1 year ago 52
MySQL Question

How do you rename a file with the just assigned auto increment id from mysql?

I am working on a form which should upload an image to my server and at the same time give it a id in the db so i can display it to the right user later on. My question is how to rename the file to the id which my mysql has given it? in my database the name for the autoincrement field is 'pictureID'. I'd like to take the value in it and name my picture like that while transfering it to my server :)

Here is my code which is mostly from w3school hehe(mysql and php aren't my strong sites)

the $_POST variables are coming from the already submitted picture..

if(isset($_POST["goOnGallery"]) OR isset($_POST["goOnCamera"])){

// Create connection
$mysqliConnection = mysqli_connect($mysqliHost, $mysqliUser, $mysqliPassword, $mysqliDatabase);
// Check connection
if (!$mysqliConnection) {die("Connection failed: " . mysqli_connect_error());}

$insertOfData = "INSERT INTO styles (userID,pictureLikes,pictureDislikes,pictureGender) VALUES ('$userID', '0', '0', '$userGender')";

if (mysqli_query($mysqliConnection, $insertOfData)) {
$target_dir = "userarchive/".$userID."/pictures/mystyles/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check file size
if ($_FILES["imageUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
} else {
echo "Error: " . $insertOfData . "<br>" . mysqli_error($mysqliConnection);

Answer Source

You're close! Just use these lines:

   if (mysqli_query($mysqliConnection, $insertOfData)) {
        $pictureID = mysqli_insert_id($mysqliConnection);
        $fe = substr($_FILES["imageUpload"]["name"], strrpos($_FILES["imageUpload"]["name"], '.'));
        $target_dir = "userarchive/".$userID."/pictures/mystyles/";
        $target_file = $target_dir . $pictureID.$fe);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download