从数组中将多个记录插入MySQL

时间:2015-01-01 00:00:58

标签: php mysql arrays mysqli

我通过下面的代码上传多张图片(它可以正常工作),但我无法将这些图片的网址插入我的数据库。我尝试了一些但不能使它工作。我的代码还没有完成,所以我还没有添加控件(filetype,filesize等)。

的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();

2 个答案:

答案 0 :(得分:1)

您需要索引$_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();
}

答案 1 :(得分:0)

确保您的数据库列&#34; image_value&#34;是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();