Solved

save image to database

Posted on 2015-02-12
4
96 Views
Last Modified: 2015-02-27
Helping  someone solve this problem ... I don't know php  but what is being attempted is to save an image to a sql database ... i've been at it 2 days now and no error is thrown but no image is saved ....  so then I tried the way you see now ... and that is not working and I think it's my syntax but I'm not sure  ...like I said I'm not a PHP guy I got dragged into the project because someone left ... any help would be appreciated

form page
 <div class="form-group">

                            <label class="col-xs-5 control-label">Upload Photo</label>

                            <div class="col-xs-7">
                                <div class="file-input-wrapper form-control">
                                    <span></span>
                                    <input type="file" value="<?php echo $userData[profile_image]?>" data-filename-placement="inside" accept="image/jpeg, image/png"/>
                                </div>
                            </div>

                        </div>

Open in new window



his Action Page
$servername = "xxxxxxx";
$username = "xxxxxx";
$password = "xxxxxxx";
$dbname = "xxxxxx";

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

$date = date("Y-d-m");

//checking the user image uplod

    $mlogo = $_FILES['userImage']['name'];

    if ($mlogo) {
        $file = $_FILES['profile_image']['name'];
        $type = $_FILES['profile_image']['type'];

        if (($type == "image/png") || ($type == "image/jpg") || ($type == "image/jpeg")) {

            $dir = "images/";

            $logo = $dir . $file;


        } else {
            $err[] = "Unsupported File Type";
           
        }

    }
  
	$sql = "UPDATE players SET name ='$_POST[name]', 
							  profile_image='$file'
		if ($mlogo) {
            move_uploaded_file($_FILES['profile_image']['tmp_name'], $logo);
        }
				

if ($conn->query($sql) === TRUE) {
	echo '<script language="javascript">';
	echo 'alert("message successfully sent")';
	echo '</script>'
}  else {
	echo '<script language="javascript">';
	echo 'alert("there was an error ")';
	echo '</script>';

    echo "Error: " . $sql . "<br>" . $conn->error;
}

Open in new window

0
Comment
Question by:dolamitejenkins
4 Comments
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 40607192
Ray Paseur has an excellent demo on uploading files in PHP but I can't find a link at the moment.  Still... what you show for your form is not adequate and I can't see if the rest of it is available.  PHP.net has an entire section about it: http://php.net/manual/en/features.file-upload.php
0
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 40608258
Haven't gone through it in detail, but 2 things of note. Firstly, your form page actually has no <form> in it. Make sure you have a <form> tag and that it's set to multipart:

<form action="yourScript.php" method="post" enctype="multipart/form-data">

Open in new window


Also, in your PHP script, you're expecting your form field to be called userImage, but in the HTML, you haven't named it, so it won't get passed to your script:

 <input type="file" name="userImage" />

Open in new window

0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 40609026
You don't really want to save an image in a database.  You want to save the image into the server file system and save the URI of the image in the database.  Uploading a file is a separate process from saving information in a database.  I can show you the part about uploading the file, below.  If you don't know PHP, you might want to look for a freelancer in your area.  Often there are PHP Meetup groups that can help you find someone who understands the security issues associated with accepting external data and saving it into your server file system and/or your database.

<?php // demo/upload_single_example.php
/**
 * Demonstrate how to upload a single file in PHP
 *
 * REQUIRED: Man Page References
 * 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.common-pitfalls.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);

// PHP 5.1+  SEE http://php.net/manual/en/function.date-default-timezone-set.php
date_default_timezone_set('America/Chicago');

// ESTABLISH THE BIGGEST FILE SIZE WE CAN ACCEPT - ABOUT 8 MB
$max_file_size = '8000000';

// ESTABLISH THE KINDS OF FILE EXTENSIONS WE WANT (USE UPPERCASE ONLY)
$file_exts = array
( 'XLS'
, 'XLSX'
, 'PDF'
, 'JPG'
)
;
$f_exts = implode(', ', $file_exts);

// ESTABLISH THE NAME OF THE DESTINATION FOLDER
$my_dir = getcwd();

// OR USE THIS TO PUT UPLOADS IN A SEPARATE FOLDER
$my_dir = 'storage';
if (!is_dir($my_dir))
{
    mkdir($my_dir);
}

// LIST OF THE ERRORS THAT MAY BE REPORTED IN $_FILES[]["error"] (THERE IS NO #5)
$errors = array
( 0 => "Success!"
, 1 => "The uploaded file exceeds the upload_max_filesize directive in php.ini"
, 2 => "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form"
, 3 => "The uploaded file was only partially uploaded"
, 4 => "No file was uploaded"
, 5 => "UNDEFINED ERROR"
, 6 => "Missing a temporary folder"
, 7 => "Cannot write file to disk"
)
;


// IF THERE IS INFORMATION POSTED
if (!empty($_POST))
{
    // IF THERE ARE ERRORS
    $error_code    = $_FILES["userfile"]["error"];
    if ($error_code)
    {
        trigger_error($errors[$error_code], E_USER_ERROR);
    }

    // GET THE FILE SIZE
    $fsize = number_format($_FILES["userfile"]["size"]);

    // SYNTHESIZE THE NEW FILE NAME FOR TEMPORARY STORAGE
    $fname = basename($_FILES['userfile']['name']);

    // FAIL IF THIS IS NOT AN ALLOWABLE EXTENSION
    $f_ext = explode('.', $fname);
    $f_ext = end($f_ext);
    $f_ext = strtoupper(trim($f_ext));
    if (!in_array($f_ext, $file_exts)) trigger_error("$f_ext NOT ALLOWED.  CHOOSE FROM $f_exts", E_USER_ERROR);

    // THE SERVER PATH TO THE FILE
    $my_path
    = getcwd()
    . DIRECTORY_SEPARATOR
    . $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // THE URL PATH TO THE FILE
    $my_url
    = $my_dir
    . DIRECTORY_SEPARATOR
    . $fname
    ;

    // MESSAGES ABOUT THE UPLOAD STATUS, IF ANY
    $msg = NULL;

    // IF THE FILE IS NEW (DOES NOT EXIST)
    if (!file_exists($my_path))
    {
        // IF THE MOVE FUNCTION WORKED CORRECTLY
        if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
        {
            $upload_success = 1;
        }
        // IF THE MOVE FUNCTION FAILED IT PROBABLY THREW A MESSAGE
        else
        {
            $upload_success = -1;
            trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
        }
    }

    // IF THE FILE ALREADY EXISTS
    else
    {
        $msg .= "<br/><b><i>$my_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-His');
            $my_bak = $my_path . '.' . $now . '.bak';
            if (!copy($my_path, $my_bak))
            {
                $msg .= "<br/><strong>Attempted Backup Failed!</strong>" . PHP_EOL;
            }
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], $my_path))
            {
                $upload_success = 2;
            }
            else
            {
                $upload_success = -1;
                trigger_error("MOVE TO $my_path FAILED", E_USER_ERROR);
            }
        }
    }

    // PREPARE A REPORT OF THE SCRIPT'S SUCCESS OR FAILURE
    if ($upload_success == 2) { $msg .= "<br/>A backup was made and the file was overwritten" . PHP_EOL; }
    if ($upload_success == 1) { $msg .= "<br/><strong>$my_url</strong> has been saved" . PHP_EOL; }
    if ($upload_success == 0) { $msg .= "<br/><strong>It was NOT overwritten.</strong>" . PHP_EOL; }
    if ($upload_success < 0)  { $msg .= "<br/><strong>ERROR: $my_url NOT SAVED - SEE WARNING FROM move_uploaded_file()</strong>" . PHP_EOL; }

    // ADD FILE SIZE AND PERMISSION INFORMATION
    if ($upload_success > 0)
    {
        $msg .= "<br/>$fsize bytes uploaded" . PHP_EOL;
        if (!chmod ($my_path, 0755))
        {
            $msg .= "<br/>chmod(0755) FAILED: fileperms() = ";
            $msg .= substr(sprintf('%o', fileperms($my_path)), -4);
        }
    }

    // SHOW THE SUCCESS OR FAILURE
    echo $msg;

    // SHOW A LINK TO THE FILE
    echo '<br/>'
    . '<a href="'
    . $my_url
    . '" target="_blank">'
    . "See: $my_url"
    . '</a>'
    ;
}


// CREATE THE FORM FOR INPUT (USING HEREDOC SYNTAX)
$form = <<<EOF
<h2>Upload a File</h2>
<p>
<form enctype="multipart/form-data" method="post">
<!--
    SOME IMPORTANT THINGS TO NOTE ABOUT THIS FORM...
    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
-->
<input type="hidden" name="MAX_FILE_SIZE" value="$max_file_size" />
Find a file to Upload ($f_exts): <input name="userfile" type="file" />
<br/>Check this box
<input autocomplete="off" type="checkbox" name="overwrite" /> to <strong>overwrite</strong> existing files
</br><input type="submit" value="Upload" />
</form>
</p>
EOF;

echo $form;

Open in new window

0
 

Author Closing Comment

by:dolamitejenkins
ID: 40636794
thanks
0

Featured Post

Space-Age Communications Transitions to DevOps

ViaSat, a global provider of satellite and wireless communications, securely connects businesses, governments, and organizations to the Internet. Learn how ViaSat’s Network Solutions Engineer, drove the transition from a traditional network support to a DevOps-centric model.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For both online and offline retail, the cross-channel business is the most recent pattern in the B2C trade space.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example, show how to set up a backup for SQL Server using a Maintenance Plan and how to schedule the job into SQL Server Agent.

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question