Hello其他程序员,
在SQL中插入时,如何将文件重命名为行ID?
让我举个例子:
<?php
// File Properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
// File extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
// File destination
$file_rename = 'ROW ID' . $file_ext; // THIS IS WHERE THE ROW ID ARE NEEDED
$file_destination = 'uploads/' . $file_rename;
if(move_uploaded_file($file_tmp, $file_destination)) {
$connect = mysqli_connect('localhost', 'root', '', 'database');
$query = "INSERT INTO images (image_id, image_url) VALUES ('', '$file_destination')"; // THIS IS THE INSERT WHERE I NEED THE ROW ID
$result = mysqli_query($connect, $query);
}
?>
赞赏所有投入。
答案 0 :(得分:0)
下面给出了处理这种情况的几种方法..
如下所示......
<?php
// File Properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
// File extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
//Perform mysql
$connect = mysqli_connect('localhost', 'root', '', 'database');
$query = "SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_name = 'images' AND table_schema = DATABASE( )"; // THIS IS WHERE YOU GET NEXT INCREMENTAL ROW ID VALUE
$next_insert_id = mysqli_query($connect, $query);
// File destination
$file_rename = $next_insert_id . $file_ext; // THIS IS WHERE THE ROW ID ARE NEEDED
$file_destination = 'uploads/' . $file_rename;
if(move_uploaded_file($file_tmp, $file_destination)) {
//Do update for that record in the database
$query = "INSERT INTO images (image_url) VALUES ('$file_destination')"; // THIS IS THE UPDATE
$result = mysqli_query($connect, $query);
}
?>
OR
如下所示......
<?php
// File Properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
// File extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
//Perform mysql
$connect = mysqli_connect('localhost', 'root', '', 'database');
$query = "INSERT INTO images (image_url) VALUES ('')"; // THIS IS THE INSERT WHERE I NEED THE ROW ID
$result = mysqli_query($connect, $query);
$last_insert_id = mysqli_insert_id();
// File destination
$file_rename = $last_insert_id . $file_ext; // THIS IS WHERE THE ROW ID ARE NEEDED
$file_destination = 'uploads/' . $file_rename;
if(move_uploaded_file($file_tmp, $file_destination)) {
//Do update for that record in the database
$query = "UPDATE images SET (image_url) VALUES ($file_destination) WHERE image_id = $last_insert_id"; // THIS IS THE UPDATE
$result = mysqli_query($connect, $query);
}
?>