dsvcqvp139098
dsvcqvp139098
2015-08-20 07:18

如何将图像插入mysql

已采纳

I am trying to upload 4 images into my file directory and also I would like to save reference to them in the database. but with my current code below, what it does is that, it inserts another row in the database instead of putting image 1 into img1 and so on.

I have given up. I don't know what is it that I am doing wrong here.

enter image description here

<?php
    if(isset($_POST['go'])) 
        {
        if(isset($_FILES['file_array']))
         {
            $name_array = $_FILES['file_array']['name'];
            $tmp_name_array = $_FILES['file_array']['tmp_name'];
            $type_array = $_FILES['file_array']['type'];
            $size_array = $_FILES['file_array']['size'];
            $error_array = $_FILES['file_array']['error'];
            $currently_item = "";
        for($i = 0; $i < count($tmp_name_array); $i++)
        {
            if(move_uploaded_file($tmp_name_array[$i],'users_posted_data/'.$name_array[$i]))
            {
                    $currently_item = current($_FILES['file_array']['name']);
                    $sql = $conn->query("INSERT INTO posts(img1, img2, img3) Values('{$currently_item}')");
                    echo $name_array[$i] . "uploaded successfully" . '<br>';
            } 
            else 
            {

            }
        }

    }
}
?>


                            <form action="" method="post" enctype="multipart/form-data">
                                <input type="file" name="file_array[]"><br><br>
                                <input type="file" name="file_array[]"><br><br>
                                <input type="file" name="file_array[]"><br><br>
                                <input type="file" name="file_array[]"><br><br> 
                                <input type="submit" name="go" value="Publish">
                        </form>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • dongmu1390 dongmu1390 6年前

    Try this:

    In the loop:

     $currently_item[] = current($_FILES['file_array']['name']);
    

    Out of the loop

       $currently_item = current($_FILES['file_array']['name']);
    
        $sql = $conn[![enter image description here][1]][1]->query("INSERT INTO posts(img1, img2, img3) 
       Values('".$currently_item[0]."','".$currently_item[1]."','".$currently_item[2]."')");
    

    Do perform the validation checks such as if value exists or not..

    点赞 评论 复制链接分享
  • doufei4418 doufei4418 6年前

    Try to pass files using LOAD_FILE function. It returns file content as a string, which you can use in INSERT or UPDATE commands -

    INSERT INTO table(id, file_name, file_data) VALUES(1, 'img.png', LOAD_FILE('img.png'));
    

    LOAD_FILE function.

    点赞 评论 复制链接分享

相关推荐