koroush
koroush

Reputation: 69

How to insert image into 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>

Upvotes: 0

Views: 73

Answers (2)

Devart
Devart

Reputation: 121902

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.

Upvotes: 1

Danyal Sandeelo
Danyal Sandeelo

Reputation: 12391

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..

Upvotes: 1

Related Questions