简体   繁体   中英

How can i select data stored in a database with PHP

the problem i am facing is i want to read a value that is auto incemented and used, my database takes the following design:

|   id   |   category   |   image   |
|   13   |    paper     |    0      |
id is auto_incremented, what i want to do is generate the id and use it as the value in image and then upload a file which has his name as the number stored in image, in this example image will be changed to 13 and the file will have the name of 13.jpg. I started my code by doing this mysql_query("INSERT INTO category (category,image) VALUES ('$name','$default_item')"); $name is written by the user and $default_item is always zero, what i want to do is change the image to equal id using update and upload an image like this $image_name = '$id' . '.jpg' move_uploaded_file($_FILES["image"]["tmp_name"], "../images/category/" . $image_name); $image_name = '$id' . '.jpg' move_uploaded_file($_FILES["image"]["tmp_name"], "../images/category/" . $image_name); Where $id is the id in the database

A few things to be mentioned:

You should not use mysql_query anymore. Use mysqli_query instead. mysql_* is deprecated and has been removed in the latest PHP version.

Secondly: Never use user generated content in an SQL query directly. Use a prepared statement . Otherwise your website is vulnerable to SQL injections.

About grabbing the auto increment value - see this thread .

Instead of using auto increment id as the image name. I will suggest generating a unique name of the image and insert that name in the database and use that name for uploading the image as well. Use below code to create the image name

$uniquesavename = time().uniqid(rand());

mysql_query("INSERT INTO category (category,image) VALUES ('$name','$uniquesavename')");

$image_name = $uniquesavename . '.jpg'
move_uploaded_file($_FILES["image"]["tmp_name"], "../images/category/" . $image_name);

By this way user uploaded image will always have a unique name.

Try this and let me know if you face any problem

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