Form to upload image to MySQL Database using PHP (Dreamweaver)

I have a very simple backend to a news section of a website. It is written in PHP in Dreamweaver using a MySQL database. It allows the user to add, amend and remove news items. The current function of the add form is adding a title (news_title), the main text (news_text) and a timestamp and ID (news_ID).

I need to add the ability to upload an image (MediumBLOB?) to the database in the same form. I have the file button in the form, but I'm stuck on the PHP end of things...

I tried adding the 'news_image' to the insert record server behaviour in dreamweaver (submit as: text) but it doesn't work. I'm sure this isn't the right way to do this but i'm new to this.....

I've attached the current PHP code before i've tried to add the image upload function.

help!
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
 
  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);
 
  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
 
$editFormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}
 
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "insert_news_item")) {
  $insertSQL = sprintf("INSERT INTO ac_news (news_title, news_text) VALUES (%s, %s)",
                       GetSQLValueString($_POST['news_title'], "text"),
                       GetSQLValueString($_POST['news_text'], "text"));
 
  mysql_select_db($database_ac, $ac);
  $Result1 = mysql_query($insertSQL, $ac) or die(mysql_error());
 
  $insertGoTo = "success.php";
  if (isset($_SERVER['QUERY_STRING'])) {
    $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
    $insertGoTo .= $_SERVER['QUERY_STRING'];
  }
  header(sprintf("Location: %s", $insertGoTo));
}
?>

Open in new window

adammorlandAsked:
Who is Participating?
 
Jason C. LevineConnect With a Mentor No oneCommented:
Hi adam,

>> I need to add the ability to upload an image (MediumBLOB?)

Overkill.

>> I tried adding the 'news_image' to the insert record server behaviour in dreamweaver (submit as: text) but it
>> doesn't work.

Nope, that's not right either.  What you need to do here is use a different type of form encoding:

enctype="multipart/form-data"

to allow for binary data to go to the server.  Instead of saving the binary to the table, you should just upload it to some folder on the site and store the image name in the table (or an altered image name, like the ID of the article plus the image extension) and call it back using an <img> tag that gets populated from the recordset.

http://www.phpfreaks.com/tutorials/36/0.php
0
 
mdouganCommented:
Here is a sample script I borrowed from somewhere (sorry I can't remember where) for doing this... the example allowed users to upload a haiku and photo.  You'll have to revisit any MySQL connection info, as I've probably stubbed it out with  "database user id"  etc.
 ************************************************************/
 
if ($_REQUEST[del])  {   
  unlink($_REQUEST[del]);
  print "<script>window.location.href='$url_this?message=deleted successfully'</script>";
}
else if ($_FILES['userfile']) {
  $message = do_upload($upload_dir, $upload_url);
  print "<script>window.location.href='$url_this?message=$message'</script>";
}
else if (!$_FILES['userfile']);
else 
	$message = "Invalid File Specified.";
 
/************************************************************
 *     List Files
 ************************************************************/
$handle=opendir($upload_dir);
$filelist = "";
while ($file = readdir($handle)) {
   if(!is_dir($file) && !is_link($file)) {
      $filelist .= "<br><a href='$upload_dir$file'>".$file."</a>";
      $filelist .= "    <a href='?del=$upload_dir$file' title='delete'>x</a>";
   }
}
 
function do_upload($upload_dir, $upload_url) {
 
	$temp_name = $_FILES['userfile']['tmp_name'];
	$file_name = $_FILES['userfile']['name']; 
	$file_type = $_FILES['userfile']['type']; 
	$file_size = $_FILES['userfile']['size']; 
	$result    = $_FILES['userfile']['error'];
	$file_url  = $upload_url.$file_name;
	$file_path = $upload_dir.$file_name;
 
	//File Name Check
    if ( $file_name =="") { 
    	$message = "Invalid File Name Specified";
    	return $message;
    }
    //File Size Check
    else if ( $file_size > 2000000) {
    	print $file_size;
        $message = "The file size is over 1MB.";
        return $message;
    }
    //File Type Check
    else if ( $file_type == "text/plain"
         || $file_type == "application/force-download"
         || $file_type == "application/octet-stream") {
        $message = "Sorry, You cannot upload any script file" ;
        return $message;
    }
 
 
    $sql="INSERT INTO haikus (haiku, image_path, background_color) VALUES ('".$_REQUEST[haiku]."','http://www.mywebsite.com/haikus/$file_name', 'FFFFFF')";
 
 
    $link = mysql_connect('ip address', 'database user id', 'database password')
       or die('Could not connect: ' . mysql_error());
 
 
    if (mysql_db_query ('database user', $sql, $link))
       {
          $result  =  move_uploaded_file($temp_name, $file_path);
  //        if (!chmod($file_path,0755))
  //   	      $message = "change permission to 755 failed.";
  //        else
            $message = ($result)?"$file_name($file_type) uploaded successfully." :
       	            "Somthing is wrong with uploading a file.";
       }
    else
       {
          $message = $sql;
//          $message = "\nFailed to insert Haiku into database";
       }
 
 
   // Closing connection
    mysql_close($link);
 
 
 
    return $message;
}
 
?>
<center>
   <font color=red><?=$_REQUEST[message]?></font>
   <br>
   <form name="upload" id="upload" ENCTYPE="multipart/form-data" method="post">
     <table>
        <tr>
           <td align='left'>Haiku</td>
           <td align='right'><input type="text" name="haiku" size='174'></td>
        </tr>
        <tr>
           <td align='left'>Upload File </td>
           <td align='right'><input type="file" id="userfile" name="userfile" size='160'></td>
        </tr>
        <tr>
           <td align='left'>&nbsp;</td>
           <td align='right'><input type="submit" name="upload" value="Upload"></td>
        </tr>
        <tr>
           <td align='center' colspan=2><b>Upload Your Haiku, put commas to seperate the lines of your poem.</b></td>
           <td align='center'>&nbsp;</td>
        </tr>
       <tr>
           <td align='center' colspan=2><hr width=70%></td>
           <td align='center'>&nbsp;</td>
        </tr>
     </table>     
   </form>
   <?=$filelist?>
</center>
 
<?
if ($_REQUEST[debug]==1) print "------------------Debugging Info----------------<br>";
if ($_REQUEST[debug]==1) print "site=$site_name<br>dir=$url_dir<br>url=$url_this<br>";
if ($_REQUEST[debug]==1) print "upload dir=$upload_dir<br>upload url=$upload_url<br>";
?>

Open in new window

0
 
mdouganCommented:
Opps, sorry, just checked and this script will upload the image to your website, and store the new file location in the MySQL database for future display.  It won't actually save the photo in your database.
0
Hire Technology Freelancers with Gigs

Work with freelancers specializing in everything from database administration to programming, who have proven themselves as experts in their field. Hire the best, collaborate easily, pay securely, and get projects done right.

 
joanne1937Commented:
I am an absolute novice at this but this is exactly what I need.  I have a insert record form that I created in Dreamweaver.  Can I use this script for my user to upload an image and where do I place it in my code.  Any help will be appreciated as a good grade depends on me learning this.
0
 
Jason C. LevineNo oneCommented:
This is a six-year old question so don't expect too much to happen.  Feel free to ask your own, new question.

Any help will be appreciated as a good grade depends on me learning this.

If this is homework, no one here will give you the answers or code as that defeats the purpose of homework and school (i.e., this is for you to learn).  We can provide general advice and guidance only.
0
 
joanne1937Commented:
This is not homework, it is a project I am doing for an internship and I am not asking how to cheat, just how to do something I have not found in tutorials or books.
0
All Courses

From novice to tech pro — start learning today.