Timothy Timothy - 1 month ago 4
MySQL Question

My loop is not working.

Seriously, my head is about to exploded. I have an html form that has roughly 20/30 input fields to allow users to upload files. I can't get the loop to record all file input fields into a database. It's only doing last one (the last file selected by the user).

I have my query inside my loop. What am I doing wrong here? Any help is really appreciated!

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "test";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}




// Getting the total number of files
$count = count($_FILES['uploads']['name']);

if (!$count)
{
echo "Upload files.";
}
else
{

// Processing each file iteratively

for ($i = 0; $i < $count; $i++)
{
$file_name = $_FILES['uploads']['name'][$i];
$ext = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

// Uploading the file

$tmp = $_FILES['uploads']['tmp_name'][$i];
$target_dir = "uploads/";
$target_file = $target_dir . basename($file_name);


$sql = "INSERT INTO uploaded_files (code, users_email, speaker_full_name, speaker_description, file)

VALUES ('".$_POST["code"]."',
'".$userRow['email']."',
'".$_POST["speaker_full_name"]."',
'".$_POST["speaker_description"]."',
'".$target_file."'
)";

if (move_uploaded_file($tmp, $target_file))
{

echo '<br>';
echo '<strong>';
echo $target_file;
echo '</strong>';
echo '<br>';
}
else
{
echo "Sorry, there was an error uploading your file";
}
}
}



if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}


mysqli_close($conn);


Thank you!
Timothy

Answer

The $sql variable is overridden on every loop, when the execution exits the for loop the variable is holding the last SQL query you build and executing it. If you move mysqli_query inside the loop it will work. You can also create a more complex query and insert all the rows in one DB roundtrip instead of doing n inserts. Also, on a side note, please read about SQL injection, your code is very not secure.

Comments