从数组中插入多条记录到MySQL

Inserting multiple records into MySQL from an array

我正在通过下面的代码上传多张图片(有效),但我无法将这些图片的网址插入到我的数据库中。我尝试了几件事,但无法让它发挥作用。我的代码还没有完成,所以我还没有添加控件(文件类型、文件大小等)。

index.php

<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">
    </div>
</form>

upload.php

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

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

    // creating a unique value here
    $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; // it echoes image urls, so everything is okay so far.
        }
    } else {
        echo "Failed";
    }

我在 echo $makeaname; 之后的 foreach 循环中使用了下面的查询,但它不起作用。我感谢任何形式的帮助或指导。

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

确保您的数据库列 "image_value" 是 BLOB 数据类型。然后试试这个代码:

$null = NULL;
$upload_image = $sqli->prepare("INSERT INTO images(image_value, type, size) VALUES (?,?,?)");
$upload_image->bind_param("bss", $null, $_FILES['images']['type'], $_FILES['images']['size']);
$upload_image->send_long_data(0, file_get_contents($makeaname));
$upload_image->execute();

您需要为 $_FILES 数组编制索引。此外,您不需要为 NULL 值绑定参数,在 SQL 中使用 NULL 文字(或者如果这是默认值,您可以完全忽略该值在架构中)。

upload_image = $sqli->prepare("INSERT INTO images(image_value, type, size) VALUES (NULL,?,?)");
$upload_image->bind_param("ss", $type, $size);
foreach ($_FILES['images']['type'] as $i => $type) {
    $size = $_FILES['images']['size'][$i];
    $upload_image->execute();
}