Php – Using PHP to upload an image and store data in MSSQL


I'm attempting to upload an image as well as add details such as; title, description and filepath into a database table.

I'm using the following code, but it isn't adding any data to the database;

(The session.php include contains the database connectivity.)

<?php include('includes/session.php');

$uploadDir = 'submitted/pictures/';

$fileName = $_FILES['file']['name'];
$tmpName  = $_FILES['file']['tmp_name'];
$fileSize = $_FILES['file']['size'];
$fileType = $_FILES['file']['type'];

$filePath = $uploadDir . $fileName;

$result = move_uploaded_file($tmpName, $filePath);
if (!$result) {
echo "Error uploading <strong>file</strong>";

    $fileName = addslashes($fileName);
    $filePath = addslashes($filePath);

$title = $_POST['title'];
$description = $_POST['description'];

$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";




The form code;

<form name="Image" enctype="multipart/form-data" action="upload-pics2.php" method="POST">
 Title <input type="text" name="title" maxlength="100" class="textbox" value="<?php echo $form->value("title"); ?>" />
 Description <textarea name="description" rows="8" cols="40" class="textbox" value="<?php echo $form->value("description"); ?>"></textarea>
 File <input type="file" name="file" accept="image/gif, image/jpeg, image/x-ms-bmp, image/x-png" size="26" class="textbox" />
 <input type="submit" name="submit" value="Upload" class="button" />

I was wondering if someone could tell me what might be going wrong?

Thank you.

Best Solution

This code do not work because of several problems.

First, you should rename one of html fields or change field name when you are checking for upload:

<input type="submit" name="Upload" value="Upload" class="button" />



Second one, this script will not store any data into DB. You should get, sanitize and write data into according fields, for example:

$title = mysql_real_escape_string($_POST['title']);
$description = mysql_real_escape_string($_POST['description']);
$query = "INSERT INTO $user_pictures (file, title, description) VALUES ('$filePath', '$title', '$description')";

You should make sure these fields present in DB, if not - you should create them:

ALTER table user_pictures ADD column description text, add column title varchar(255);