Link to home
Start Free TrialLog in
Avatar of sanchit gupta
sanchit gupta

asked on

Inserting images in database PDO

I have created a very basic form for inserting data in database PDO. I'm done with the url, name and title but got stucked with the image. How to get image inserted into database through the "folder". I also want to fetch all the details onto some another page.
Any help in styling up these would also be highly appreciated.
<?php
ob_start();
include ("./inc/header.inc.php");
$fileToUpload="";
if(isset($_POST['newpost'])) {
    $urlInput=$_POST['urlInput'];
    $fileToUpload=$_FILES['fileToUpload']['name'];
    $title=$_POST['title'];
    $userid = Login::isLoggedin();
    $filename = $_FILES['fileToUpload']['name'];
    $filetemp = $_FILES['fileToUpload']['tmp_name'];
    $filesize = $_FILES['fileToUpload']['size'];
    $filebasename = basename($_FILES['fileToUpload']['name']);
    $dir="userdata/folder/";
    $finaldir=$dir.$filebasename;
    move_uploaded_file($filetemp,$finaldir);
    DB::query('INSERT INTO links VALUES (\'\', :urlInput, :fileToUpload, :title, NOW(), :userid, 0)', array(':urlInput'=>$urlInput, ':fileToUpload'=>$fileToUpload, ':title'=>$title, ':userid'=>$userid));
}

?>

<form action="submit.php" method="post">
        <p><label><b>URL</b></label><br>
<input type="url" name="urlInput" value="" placeholder="" required><p />
        <p><label><b>Image</b></label><br>
<input type="file" name="fileToUpload" value="" placeholder="" accept="image/*" required><p />
        <p><label><b>Title</b></label><br>
<input type="text" name="title" value="" placeholder="" required><p />
<input type = "submit" name="newpost" value="Submit"/>
</form>

Open in new window

Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Standard "good practices" would not put an image into the database.  Instead, store the image file in the server file system and store the URL (or similar location pointer) in the database.
Avatar of sanchit gupta
sanchit gupta

ASKER

@Ray that is exactly what i'm trying to do.
Good.  So what seems to be going wrong?
On being clicked on submit is says a error "Undefined index fileToUpload"
ASKER CERTIFIED SOLUTION
Avatar of Imran Ali
Imran Ali
Flag of Pakistan image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Here's a complete example of a PHP file upload script.  It allows for multiple file uploads, tests for errors and produces sensible error messages, etc.  You may not need all of it, and you can just carve out the parts you need.  It also has links to the relevant man pages.
<?php // demo/upload_example.php
/**
 * Demonstrate how to upload one or more files, using HTML5 and PHP
 *
 * REQUIRED: Man Page References
 * http://www.w3schools.com/tags/att_input_multiple.asp
 *
 * http://php.net/manual/en/reserved.variables.files.php
 * http://php.net/manual/en/features.file-upload.php
 * http://php.net/manual/en/features.file-upload.post-method.php
 * http://php.net/manual/en/features.file-upload.common-pitfalls.php
 * http://php.net/manual/en/features.file-upload.errors.php
 * http://php.net/manual/en/features.file-upload.multiple.php
 *
 * http://php.net/manual/en/function.move-uploaded-file.php
 *
 * IMPORTANT: If dealing with large files
 * http://php.net/manual/en/ini.core.php#ini.upload-max-filesize
 * http://php.net/manual/en/ini.core.php#ini.post-max-size
 * http://php.net/manual/en/info.configuration.php#ini.max-input-time
 */
error_reporting(E_ALL);

// MAY NOT BE NEEDED - CHECK PHP_INI PARAMETERS FOR YOUR TIMEZONE
date_default_timezone_set('America/Chicago');

// ESTABLISH THE NAME OF THE DESTINATION FOLDER ('storage' DIRECTORY)
$storage = 'storage';
if (!is_dir($storage))
{
    mkdir($storage);
}

// ESTABLISH THE BIGGEST FILE SIZE WE WILL ACCEPT - ABOUT 8 MB
$max_file_size = 8 * 1024 * 1024;

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE WILL ACCEPT
$file_exts = array
( 'jpg'
, 'gif'
, 'png'
, 'txt'
, 'pdf'
, 'doc'
, 'docx'
)
;

// ARRAY OF ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( UPLOAD_ERR_OK         => "Success!"
, UPLOAD_ERR_INI_SIZE   => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, UPLOAD_ERR_FORM_SIZE  => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, UPLOAD_ERR_PARTIAL    => "The uploaded file was only partially uploaded"
, UPLOAD_ERR_NO_FILE    => "No file was uploaded"
, 5                     => "UNDEFINED ERROR #5"
, UPLOAD_ERR_NO_TMP_DIR => "Missing a temporary folder"
, UPLOAD_ERR_CANT_WRITE => "Cannot write file to disk"
, UPLOAD_ERR_EXTENSION  => "A PHP extension stopped the file upload"
)
;


// IF WE HAVE GOT SOMETHING IN $_POST - RUN THE ACTION SCRIPT
if (!empty($_POST))
{
    echo "<h2>Results: File Upload</h2>" . PHP_EOL;

    // ACTIVATE THIS TO SEE WHAT IS COMING THROUGH IN THE REQUEST
    // echo "<pre>"; var_dump($_FILES); var_dump($_POST); echo "</pre>";

    // REORGANIZE THE CONTENTS OF $_FILES SO WE CAN USE AN ITERATOR MORE SENSIBLY
    $nf = count($_FILES['userfile']['name']);
    while ($nf)
    {
        $nf--;
        $my_uploaded_files[$nf]['name']     = $_FILES['userfile']['name'][$nf];
        $my_uploaded_files[$nf]['type']     = $_FILES['userfile']['type'][$nf];
        $my_uploaded_files[$nf]['tmp_name'] = $_FILES['userfile']['tmp_name'][$nf];
        $my_uploaded_files[$nf]['error']    = $_FILES['userfile']['error'][$nf];
        $my_uploaded_files[$nf]['size']     = $_FILES['userfile']['size'][$nf];
    }

    // ITERATE OVER THE COLLECTION OF UPLOADED FILES
    foreach ($my_uploaded_files as $my_uploaded_file)
    {
        // SKIP OVER EMPTY SPOTS - NOTHING UPLOADED
        $error_code = $my_uploaded_file["error"];
        if ($error_code == UPLOAD_ERR_NO_FILE) continue;

        // IF THERE ARE ERRORS
        if ($error_code != UPLOAD_ERR_OK)
        {
            $error_message = $errors[$error_code];
            trigger_error("Upload error code: $error_code: $error_message", E_USER_WARNING);
            continue;
        }

        // SYNTHESIZE THE NEW FILE NAME
        $f_type = explode('.', basename($my_uploaded_file['name']));
        $f_type = end($f_type);
        $f_type = trim(strtolower($f_type));

        $f_name = explode('.', basename($my_uploaded_file['name']));
        $f_name = current($f_name);
        $f_name = trim(strtolower($f_name));

        // SERVER PATH TO THE NEW FILE
        $my_file_path
        = getcwd()
        . DIRECTORY_SEPARATOR
        . $storage
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // URL PATH TO THE NEW FILE
        $my_file_url
        = $storage
        . DIRECTORY_SEPARATOR
        . $f_name
        . '.'
        . $f_type
        ;

        // OPTIONAL TEST FOR ALLOWABLE EXTENSIONS
        if (!in_array($f_type, $file_exts))
        {
            trigger_error("$f_type Not allowed", E_USER_WARNING);
            continue;
        }

        // GET THE FILE SIZE
        $file_size = number_format($my_uploaded_file["size"]);

        // IF THE FILE IS NEW (DOES NOT EXIST)
        if (!file_exists($my_file_path))
        {
            // IF THE MOVE FUNCTION WORKED CORRECTLY
            if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_file_path))
            {
                $upload_success = 1;
            }
            // IF THE MOVE FUNCTION FAILED
            else
            {
                $upload_success = -1;
            }
        }

        // IF THE FILE ALREADY EXISTS
        else
        {
            echo "<br/><b><i>$my_file_url</i></b> already exists." . PHP_EOL;

            // SHOULD WE OVERWRITE THE FILE? IF NOT
            if (empty($_POST["overwrite"]))
            {
                $upload_success = 0;
            }
            // IF WE SHOULD OVERWRITE THE FILE, TRY TO MAKE A BACKUP
            else
            {
                $now    = date('Y-m-d\THis');
                $my_bak = $my_file_path . '.' . $now . '.bak';
                if (!copy($my_file_path, $my_bak))
                {
                    trigger_error("Backup Failed for $my_file_url", E_USER_WARNING);
                }
                if (move_uploaded_file($my_uploaded_file['tmp_name'], $my_file_path))
                {
                    $upload_success = 2;
                }
                else
                {
                    $upload_success = -1;
                }
            }
        }

        // REPORT OUR SUCCESS OR FAILURE
        if ($upload_success == 2) { echo "<br/>It has been overwritten." . PHP_EOL; }
        if ($upload_success == 1) { echo "<br/><b>$my_file_url</b> has been saved." . PHP_EOL; }
        if ($upload_success == 0) { echo "<br/><b>It was NOT overwritten.</b>" . PHP_EOL; }
        if ($upload_success < 0)  { echo "<br/><b>ERROR: $my_file_url NOT SAVED - SEE WARNING FROM <i>move_uploaded_file()</i></b>" . PHP_EOL; }
        if ($upload_success > 0)
        {
            echo "$file_size bytes uploaded." . PHP_EOL;
            if (!chmod ($my_file_path, 0644))
            {
                echo '<br/>chmod(0644) FAILED: fileperms() = ';
                echo substr(sprintf('%o', fileperms($my_file_path)), -4);
            }
            echo '<br/>See the file: <a target="_blank" href="' . $my_file_url . '">' . $my_file_url . '</a><br/>' . PHP_EOL;
        }
    } // END FOREACH ITERATOR - EACH ITERATION PROCESSES ONE FILE
} // END ACTION SCRIPT


// CREATE THE HTML FORM USING HEREDOC NOTATION
$form = <<<EOF
<h2>Upload file(s)</h2>
<!--
    SOME IMPORTANT THINGS TO NOTE ABOUT THIS FORM...
    REQUIRES THE HTML5 DOCTYPE
    ENCTYPE= ATTRIBUTE IN THE HTML <FORM> TAG
    MAX_FILE_SIZE HIDDEN CONTROL MUST PRECEDE THE FILE INPUT CONTROLS
    INPUT NAME= IN TYPE=FILE DETERMINES THE NAME YOU FIND IN _FILES ARRAY
    ABSENCE OF ACTION= ATTRIBUTE IN <FORM> TAG CAUSES POST TO SAME URL
-->
<form name="UploadForm" enctype="multipart/form-data" method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
<p>
Find the file(s) you want to upload and click the "Upload" button below.
</p>

<input type="file" multiple name="userfile[]" size="80" />

<br/>Check this box <input autocomplete="off" type="checkbox" name="overwrite" /> to <b>overwrite</b> existing files.
<input type="submit" value="Upload" />
</form>
EOF;

echo $form;

Open in new window

@ImranAli it worked!

i want to fetch image too. how to do that?
to fetch image
Use a hyperlink.
If you want to fetch from database & display it.
<?php

/*
	To Fetch image from DB
*/
 $selectUserImage = DB::query("SELECT FROM links WHERE userid = '".$userid."'");
 $userImagePath = $selectUserImage['fileToUpload'];
 $fileTitle = $selectUserImage['title']; 
 ?>
 <img src="<?=$userImagePath?>" alt="<?=$fileTitle?>" height="auto" >

Open in new window

it says undefined index for title and filetoupload
@sanchit
The code I posted was to give you idea on how you can fetch image record.
I can help you with code if you let me know what Database library you are using?

Thanks.
User generated imagein image it is stored like "image.jpg" unable to include it in photo
I am still not sure which CMS or library you are working with?

You can check this code in native PHP as a reference.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$selectUserImage = "SELECT image,title FROM links WHERE user_id = '".$userid."'";
$result = $conn->query($sql);
$rowImage = $result->fetch_assoc();

$userImagePath = $rowImage['image'];
$fileTitle = $rowImage['title']; 

?>
<img src="<?=$userImagePath?>" alt="<?=$fileTitle?>" height="auto" >

Open in new window

SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Ray I agree with your comment.

Moreover, the code I posted was to give idea & is not the production code.

Thanks.
stale question