简体   繁体   中英

Error Upload To Mysql Database

I create upload image and move image to upload folder. When someone uploads image that mysql_insert_id() will insert unique id (1, 2, 3, 4, 5 so on....) and image extension (jpg, gif, png), I need the result looks like this (1.jpg, 2.gif, 3.png, 4.jpg, 5.gif, 6.png so on.......)

I think the issue is in this bit of code:

mysql_query("INSERT INTO users VALUES('', '$image_file')") or die (mysql_error());
$image_id = mysql_insert_id();
$image_file = $image_id.'.'.$extension;

Looks as though you're using $image_file in the sql before it's been created.. Try this instead:

$image_file = $image_id.'.'.$extension;
mysql_query("INSERT INTO users VALUES('', '$image_file')") or die (mysql_error());
$image_id = mysql_insert_id();

Erm no

After another look at your code I can't see where you're setting $image_file for use in the sql at all, I noticed you were using the returned mysql_insert_id after posting my answer, sorry for the confusion there.

I think you need to generate the $image_file before using it in the sql, and again after as you look to be wanting to use the returned mysql_insert_id.

$image_file = $_FILES['image']['name'];
mysql_query("INSERT INTO users VALUES('', '$image_file')") or die (mysql_error());
$image_id = mysql_insert_id();

Also

As you are renaming the file you also need to update the stored image name in the database after creating the record:

$image_file = $_FILES['image']['name'];
mysql_query("INSERT INTO users VALUES('', '$image_file')") or die (mysql_error());
$image_id = mysql_insert_id();
$image_file = $image_id . '.' . $extension;
move_uploaded_file($_FILES["image"]["tmp_name"], "upload/".$image_file);
mysql_query("UPDATE users SET image_column = '{$image_file}' WHERE id_column = {$image_id}") or die(mysql_error());

Because you haven't used the columns names in your sql statements I've used generic terms you will need to insert your own columns instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM