I have an images table in database which holds ID(it's an auto increment post number), filename(uploaded files own name) and timestamp etc..
I upload files to a directory and add the info to the table. I'd like to change the filename with the ID number(or order number) from database table in the directory after I upload and put info in the database table.
keep in mind that I'm somewhat beginner at php and I'd like to learn with the explanation of the code. like which string is for what, which method is for what..
thank you very much for your time.
here's some code:
//CONNECTS TO DATABASE
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
if (!$link)
{
die('Could not connect: '. mysqli_error());
}
//SELECTS DATABASE
$db_selected = mysqli_select_db($link, DB_NAME);
if (!$db_selected)
{
die('Can\'t use' . DB_NAME . ': ' . mysqli_error());
}
//FILE NAME
$userNameSend = $_FILES ['user-file']['name'];
//INSERTS INTO DATABASE
$sql = "INSERT INTO images (USERIMAGENAME) VALUES ('$userNameSend')";
//CONNECTION CHECK
if (!mysqli_query($link, $sql))
{
die('Error: ' . mysqli_error());
}
else
{
header('Location: ./board.php');
}
}
mysqli_close($link);
After the insert (if successful) get the id of the last inserted row:
$last_id = mysqli_insert_id($link);
Get the extension of the uploaded file:
$ext = pathinfo($userNameSend, PATHINFO_EXTENSION);
Then rename the uploaded file with ($upload_dir
is the path to the directory where you are saving the files):
rename($upload_dir.$userNameSend, $upload_dir.$last_id.".".$ext);