Inserting multiple records into MySQL from an array


I am uploading multiple images via the code below, but I don’t know how to insert these images into my MySQL database in bulk. Can you help me?

<form action="upload.php" method="post" enctype="multipart/form-data">
    <div id="file_container">
        <input name="images[]" multiple type="file" id="file[]"/><br/>
        <input type="submit">


$target = "upload/";
$test = 1;

foreach ($_FILES['images']['name'] as $key => $value) {
    $path = $_FILES['images']['name'][$key];
    $ext = pathinfo($path, PATHINFO_EXTENSION);

    $name = md5($name);
    $generate1 = md5(date('Y-m-d H:i:s:u'));
    $randomizer = uniqid($name);
    $name = $name . $generate1 . $randomizer;
    $makeaname = $target . $name . "." . $ext;

    if ($test == 1) {
        if (move_uploaded_file($_FILES['images']['tmp_name'][$key], $makeaname)) {
            echo "<strong>" . $value . "</strong> successful <br />\n";
            echo $makeaname;
    } else {
        echo "Failed";

Generally I use a simple insert query like below but this time I THINK I need to use this query in a foreach in order to make itwork for x times, yet I can’t do it.

$upload_image = $sqli->prepare("INSERT INTO metadata_images(metadata_image_value, type, size) VALUES (?,?,?)");
$upload_image->bind_param("sss", $makeaname, $_FILES['images']['type'], $_FILES['images']['size']);

This is an example of what I’ve used recently for a similar situation where I’ve wanted to do a bulk insert (this uses PDO):

$insertQuery = array();
$insertData = array();
foreach ($rights_status['add'] AS $row ) {
    $insertQuery[] = '(?,?)';
    $insertData[] = $rank;
    $insertData[] = $row['id'];

if (!empty($insertQuery)) {
    $sql .= implode(', ', $insertQuery);
    $stmt = $this->db->prepare($sql);

The $insertQuery needs as many ? as the number of fields that you’ll be inserting into. I believe that you need a $insertData for each field (not tried it inserting more then 2 fields. When I checked the prepared statement (PDO has a function called debugDumpParams() ), it shows that the query will insert as many rows as I’ve got data for.

btw for hashing md5 has been rainbow tabled to death. If you’re using version 5.5 or higher of PHP, then you have available a group of functions for dealing with hashed values.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.