-2

I'm creating a HTML form to insert input and file values in their respective tables using same php script to execute this. When I fill the input text and select images to send the path of all their to a table, the php script inserts several lines in one table according to the number of images that i select for send and this is incorrect because the table just have to store one record and the another table has to store images names with the recently created ID.

I found some similars questions about, but i didin't find a correct way to solve this:

  1. PHP multiple records insert
  2. MYSQL Insert Submit Button PHP
  3. PHP multiple records insert
  4. how to insert multiple records in php

In this case i have 2 tables on Mysql: cars_tbl e images_tbl. Below are their structure:

cars_tbl

carID | carName
--------------------
01    | Volvo
02    | GM
03    | Ford
xx    | xxxxxxxxxx

images_tbl

imageID | image       | carID
-------------------------------
01      | 0001.jpg    | 01
02      | 0551.jpg    | 01
03      | 08591.jpg   | 02
04      | 074581.jpg  | 02
05      | 785581.jpg  | 03

On table images_tbl, *the carID column, is a foreing key of ID column from cars_tbl.

Below are the basic HTML form code that i'm using for this:

<form action="upload.php" method="post" enctype="multipart/form-data">

<label for="carName">Car Name:</label><br>
  <input type="text" id="carName" name="carName"><br>

<label for="image">Select images:</label><br>
<input type="file" id="file" name="file" multiple>

 <input type="submit" name="submit" value="ADD">

</form>

And finally, the PHP script (upload.php) that has a function to insert into carName input to cars_tbl table and insert into the images names and carID on images_tbl table:

<?php

include 'configDB.php';

// prepare and bind
$stmt = $db->prepare("INSERT INTO cars_tbl (carName) VALUES (?)");
$stmt->bind_param("s", $carName);

// set parameters and execute
$carName = $_POST['carName'];
$stmt->execute();
$stmt->close();

$last_id = $db->insert_id;

if(!empty($_FILES)){

    // File path configuration 
    $uploadDir = "uploads/"; 
    $fileName = basename($_FILES['file']['name']); 
    $uploadFilePath = $uploadDir.$fileName; 

    // Upload file to server 
    if(move_uploaded_file($_FILES['file']['tmp_name'], $uploadFilePath)){ 
        // Insert file information in the database 
        $insert = $db->query("INSERT INTO images_tbl (image, carID) VALUES ('".$fileName."', '".$last_id."')"); 
    } 
        echo "Car added. ID: .$last_id.";

$db->close();

}

?>

Based on the information above, when I fill the input form carName and select images on file input, after i click submit button, the php script (upload.php) uploads selected images to uploads folder correctly, but on cars_tbl table, the script add several lines according to the number of images that i send and at the same time, the script add images name into images_tbl table, but the carID column is not only unique ID for all added images, but the carID is on a sequence number instead of the recently created ID from cars_tbl table.

UPDATED

The results that i would like to happen is similar the table below:

Suppose that i fill carName input with BMW name and i selected 3 images clicking on file browser button then i click on submit button. The php script should insert the data into 2 tables cars_tbl and images_tbl like below:

cars_tbl table

carID | carName
--------------------
xx    | xxxxx
xx    | xxxxx
xx    | xxxxx
04    | BMW

images_tbl table

imageID | image       | carID
-------------------------------
xx      | xxxxxxxx    | xx
xx      | xxxxxxxx    | xx
xx      | xxxxxxxx    | xx
05      | 782221.jpg  | 04
06      | 711581.jpg  | 04
07      | we3444.jpg  | 04

In this case, where i have to modify my script (upload.php) to insert, after click on submit button, only one register into cars_tbl table and the selected images names into images_tbl table related to recently created carID?

Michel Xavier
  • 133
  • 3
  • 14
  • 1
    Disable submit button to avoid double clicks or mutiple clicks, Which cause multiple form submissions – Ajith Apr 08 '20 at 12:56
  • 1
    Do you have any Triggers or other Procedures that are adding SQL rows on this table? – Martin Apr 08 '20 at 13:29
  • 1
    `multiple` is not a valid or useful attribute in a `
    – ADyson Apr 08 '20 at 13:36
  • 1
    Your PHP code looks like you're uploading images one at a time, but your wording on your question suggests you're uploading images in blocks of several at once, can you clarify which it is? – Martin Apr 08 '20 at 13:36
  • Martin is right. This PHP code can only deal with uploading one file at a time. So either this isn't the correct version of your code, or there's something else you're not telling us. – ADyson Apr 08 '20 at 13:40
  • 1
    Also a **warning:** Your code may be vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could steal, change, or even delete your data. (not as easy with a filename admittedly, but still you should use best practices at all times) – ADyson Apr 08 '20 at 13:41
  • 2
    And **never** get your web app to login to the database as root. Root can do whatever it likes, so on top of the SQL injection vulnerabilities this just leaves your database an open book for hackers. Instead create a separate user account specifically for this application which has only the permissions it actually _needs_ in order to work properly. Don't even use the root account as a shortcut during development or testing, because you need to test your account permissions as well - otherwise when you go live you might have unexpected errors relating to the user account setup. – ADyson Apr 08 '20 at 13:41
  • Anyway [this](https://stackoverflow.com/questions/2704314/multiple-file-upload-in-php) ought to help you with the job of adapting the PHP code to upload multiple images per car. – ADyson Apr 08 '20 at 13:47
  • So, the database connection config in php script above is just an example. My connecting config file is another. The multiple tag that i put in
    i didn't see and was a mistake and i removed. As to the question of prepared statements, if you repare, the php script is wrote in prepared statements on mysqli insert into. I updated the question to clarify my doubt.
    – Michel Xavier Apr 08 '20 at 15:09
  • 1
    " the php script is wrote in prepared statements on mysqli insert into"...not in the code you've shown, it isn't. That code is vulnerable. – ADyson Apr 08 '20 at 15:39
  • 1
    Anyway my last comment with this link: https://stackoverflow.com/questions/2704314/multiple-file-upload-in-php should help you with uploading multiple files and processing them all. – ADyson Apr 08 '20 at 15:40

1 Answers1

2

Your PHP code looks like you're uploading images one at a time, but your HTML form is accepting multiple images.

In this issue the structure of the $_FILES tag will be completely different and not transferable between these two types of $_FILES.


As general practise you should add a CSRF token to your POSTing form, which will also avoid this duplication, the form may be submitted multiple times but it will only be accepted the first time.

So your form would have a unique token <input type='hidden' name='randomName' value='<?php print $_SESSION['randomValueEachPageLoad'];?>'>

Then, on your receiving page, you do this:

if($_POST['randomName'] === $_SESSION['randomValueEachPageLoad']){
    // Do all of your stuff with the form data.
}
unset($_SESSION['randomValueEachPageLoad']);

As noted by ADyson remove the multiple from your <form> element.


As also mentioned by ADyson, you are logging into your SQL as the root user, this is highly unwise and is a significant security risk; if someone can access your PHP or even post their own data to your forms (as you don't have CSRF protection or universal parameterised queries) then they can do anything with your SQL.....

Martin
  • 22,212
  • 11
  • 70
  • 132
  • Thanks for your feedback. So, the database connection config in php script above is just an example. My connectiong config file is another. The *multiple* tag that i put in
    i didn't see and was a mistake and i removed. In general, i would like to edit my script to insert into cars_tbl and images_tbl at the same time. In this case, one record into cars_tbl and one or more images names into images_tbl. Thanks for tips.
    – Michel Xavier Apr 08 '20 at 14:51