www.webdeveloper.com
Results 1 to 12 of 12

Thread: upload to folder and write file name in mySQL

  1. #1
    Join Date
    Oct 2012
    Posts
    8

    upload to folder and write file name in mySQL

    I've looked all over and have basically found the same code for this issue, but it doesn't work for me. I'm not a real programmer, more of a graphic artist who has had to learn stuff, so it is hard to figure this out.

    I have a form. In the form there is an upload file code. I want to have the user click that, select the image he wants to put on the site (in a folder called 'pix') and have the name of the file written to my database (into a field called 'photo').

    I simply can not figure out how to make the code I keep finding all over work for me. I rely on Dreamweaver for a lot of my PHP. Anyway, here is the entire page. How do I do this? I'm pulling my hair out.

    Thanks.
    Mightyhokie

    Code:
    <?php require_once('../Connections/blog.php'); ?>
    <?php require_once('sessonCheck.php'); ?>
    
    
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
    {
      if (PHP_VERSION < 6) {
        $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"] == "insertRecord")) {
      $insertSQL = sprintf("INSERT INTO main (blogID, title, content, photo, `date`) VALUES (%s, %s, %s, %s, %s)",
                           GetSQLValueString($_POST['blogID'], "int"),
                           GetSQLValueString($_POST['title'], "text"),
                           GetSQLValueString($_POST['content'], "text"),
                           GetSQLValueString($_POST['photo'], "text"),
                           GetSQLValueString($_POST['date'], "text"));
    
      mysql_select_db($database_blog, $blog);
      $Result1 = mysql_query($insertSQL, $blog) or die(mysql_error());
      
    
      $insertGoTo = "blogList.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      }
      header(sprintf("Location: %s", $insertGoTo));
    }
    
    ?>
    
    
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    <link href="blog.css" rel="stylesheet" type="text/css">
    </head>
    
    <body>
    
    <div class="wrapper">
    
    
    
    <form action="<?php echo $editFormAction; ?>" method="POST" name="insertRecord" enctype="multipart/form-data">
    
        <table width="200" border="1">
          <tr>
            <td>Date:</td>
            <td><input name="date" type="text" size="10" maxlength="10"></td>
            
          </tr>
          <tr>
            <td>Title:</td>
            <td><input name="title" type="text" size="50" maxlength="100"></td>
            
          </tr>
          <tr>
            <td>Content:</td>
            <td><textarea name="content" cols="100" rows="10"></textarea></td>
            
          </tr>
          <tr>
            <td>Image:</td>
            <td><input type="file" name="photo" size="40"></td>
            
          </tr>
          
          <tr>
            <td colspan="2"><input name="submit" type="submit" value="Submit"></td>
            
          </tr>
          
        </table>
        <input type="hidden" name="MM_insert" value="insertRecord">
        
        <input name="blogID" type="hidden" value="blogID">
        
    </form>
    
    
    </div> <!--end wrapper-->
    
    
    
    
    
    </body>
    </html>

  2. #2
    Join Date
    May 2003
    Posts
    598
    It looks like you have the code for logging the form info in the database...is that working? ...your just not able to handle the upload?
    We do precision guesswork

  3. #3
    Join Date
    Oct 2012
    Posts
    8
    when i fill out the form and select the image to upload it IS uploading that image. What i need now is for it to write the name of the image in the database for later reference. It is driving me crazy. I have tried half a dozen techniques (all of which are very similar) but no joy. Here is the working code for the add.php page, as well as the update.php, minus the ability for it write the name to the DB. If you could tell me how to make it work i would be very grateful. Please help a brother out! =D

    add.php
    Code:
    <?php require_once('../Connections/blog.php'); ?>
    <?php require_once('sessonCheck.php'); ?>
    
    
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
    {
      if (PHP_VERSION < 6) {
        $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"] == "insertRecord")) {
      $insertSQL = sprintf("INSERT INTO main (blogID, title, content, photo, `date`) VALUES (%s, %s, %s, %s, %s)",
                           GetSQLValueString($_POST['blogID'], "int"),
                           GetSQLValueString($_POST['title'], "text"),
                           GetSQLValueString($_POST['content'], "text"),
                           GetSQLValueString($_POST['photo'], "text"),
                           GetSQLValueString($_POST['date'], "text"));
    
      mysql_select_db($database_blog, $blog);
      $Result1 = mysql_query($insertSQL, $blog) or die(mysql_error());
      
    /* //////////////////////////////////////////////////////   UPLOAD TO SERVER*/
    define("UPLOAD_DIR", "pix/");
    
    if (!empty($_FILES["photo"])) {
        $myFile = $_FILES["photo"];
    
        if ($myFile["error"] !== UPLOAD_ERR_OK) {
            echo "<p>An error occurred.</p>";
            exit;
        }
    
    
    
    
        // ensure a safe filename
        $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
    
        // don't overwrite an existing file
        $i = 0;
        $parts = pathinfo($name);
        while (file_exists(UPLOAD_DIR . $name)) {
            $i++;
            $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
        }
    
        // preserve file from temporary directory
        $success = move_uploaded_file($myFile["tmp_name"],
            UPLOAD_DIR . $name);
        if (!$success) { 
            echo "<p>Unable to save file.</p>";
            exit;
        }
    
        // set proper permissions on the new file
        chmod(UPLOAD_DIR . $name, 0644);
    }
    
    /* //////////////////////////////////////////////////////   END UPLOAD TO SERVER*/
    
    
    
      $insertGoTo = "list.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      }
      header(sprintf("Location: %s", $insertGoTo));
    }
    
    ?>
    
    
    
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    <link href="blog.css" rel="stylesheet" type="text/css">
    </head>
    
    <body>
    
    <div class="wrapper">
    
    
    <div class="blogTitle"> Add New Blog</div>
    
    <form action="<?php echo $editFormAction; ?>" method="POST" name="insertRecord" enctype="multipart/form-data">
    
        <table width="200" border="0">
          <tr>
            <td>Date:</td>
            <td><input name="date" type="text" size="10" maxlength="10"></td>
            
          </tr>
          <tr>
            <td>Title:</td>
            <td><input name="title" type="text" size="50" maxlength="100"></td>
            
          </tr>
          <tr>
            <td>Content:</td>
            <td><textarea name="content" cols="100" rows="10"></textarea></td>
            
          </tr>
          <tr>
            <td>Image:</td>
            <td><input type="file" name="photo" size="40"></td>
            
          </tr>
          
          <tr>
            <td colspan="2"><input name="submit" type="submit" value="Submit"></td>
            
          </tr>
          
        </table>
        <input type="hidden" name="MM_insert" value="insertRecord">
        
        <input name="blogID" type="hidden" value="blogID">
        
    </form>
    
    
    </div> <!--end wrapper-->
    </body>
    </html>

  4. #4
    Join Date
    Oct 2012
    Posts
    8
    update.php
    Code:
    <?php require_once('../Connections/blog.php'); ?>
    <?php require_once('sessonCheck.php'); ?>
    <?php
    if (!function_exists("GetSQLValueString")) {
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
    {
      if (PHP_VERSION < 6) {
        $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_update"])) && ($_POST["MM_update"] == "editRecord")) {
      $updateSQL = sprintf("UPDATE main SET title=%s, content=%s, photo=%s, `date`=%s WHERE blogID=%s",
                           GetSQLValueString($_POST['title'], "text"),
                           GetSQLValueString($_POST['content'], "text"),
                           GetSQLValueString($_POST['photo'], "text"),
                           GetSQLValueString($_POST['date'], "text"),
                           GetSQLValueString($_POST['blogID'], "int"));
    
      mysql_select_db($database_blog, $blog);
      $Result1 = mysql_query($updateSQL, $blog) or die(mysql_error());
    
      $updateGoTo = "list.php";
      if (isset($_SERVER['QUERY_STRING'])) {
        $updateGoTo .= (strpos($updateGoTo, '?')) ? "&" : "?";
        $updateGoTo .= $_SERVER['QUERY_STRING'];
      }
      header(sprintf("Location: %s", $updateGoTo));
    }
    
    $colname_rsUpdate = "1";
    if (isset($_GET['blogid'])) {
      $colname_rsUpdate = $_GET['blogid'];
    }
    mysql_select_db($database_blog, $blog);
    $query_rsUpdate = sprintf("SELECT blogID, title, content, photo, `date` FROM main WHERE blogID = %s", GetSQLValueString($colname_rsUpdate, "int"));
    $rsUpdate = mysql_query($query_rsUpdate, $blog) or die(mysql_error());
    
    /* //////////////////////////////////////////////////////   UPLOAD TO SERVER*/
    define("UPLOAD_DIR", "pix/");
    
    if (!empty($_FILES["photo"])) {
        $myFile = $_FILES["photo"];
    
        if ($myFile["error"] !== UPLOAD_ERR_OK) {
            echo "<p>An error occurred.</p>";
            exit;
        }
    
        // ensure a safe filename
        $name = preg_replace("/[^A-Z0-9._-]/i", "_", $myFile["name"]);
    
        // don't overwrite an existing file
        $i = 0;
        $parts = pathinfo($name);
        while (file_exists(UPLOAD_DIR . $name)) {
            $i++;
            $name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
        }
    
        // preserve file from temporary directory
        $success = move_uploaded_file($myFile["tmp_name"],
            UPLOAD_DIR . $name);
        if (!$success) { 
            echo "<p>Unable to save file.</p>";
            exit;
        }
    
        // set proper permissions on the new file
        chmod(UPLOAD_DIR . $name, 0644);
    }
    
    /* //////////////////////////////////////////////////////   END UPLOAD TO SERVER*/
    
    
    
    
    
    $row_rsUpdate = mysql_fetch_assoc($rsUpdate);
    $totalRows_rsUpdate = mysql_num_rows($rsUpdate);
    ?>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Untitled Document</title>
    <link href="blog.css" rel="stylesheet" type="text/css">
    </head>
    
    <body>
    
    <div class="wrapper">
    
    <div class="blogTitle"> Add New Blog</div>
    
    <form method="POST" name="editRecord" id="editRecord" enctype="multipart/form-data" action="<?php echo $editFormAction; ?>">
    
        <table width="200" border="1">
          <tr>
            <td>Date:</td>
            <td><input name="date" type="text" value="<?php echo $row_rsUpdate['date']; ?>" size="10" maxlength="10"></td>
            
          </tr>
          <tr>
            <td>Title:</td>
            <td><input name="title" type="text" value="<?php echo $row_rsUpdate['title']; ?>" size="50" maxlength="100"></td>
            
          </tr>
          <tr>
            <td>Content:</td>
            <td><textarea name="content" cols="100" rows="10"><?php echo $row_rsUpdate['content']; ?></textarea></td>
            
          </tr>
          <tr>
            <td>Image:</td>
            <td><input type="file" name="photo" size="40"></td>
            
          </tr>
          
          <tr>
            <td colspan="2"><input name="submit" type="submit" value="Submit"></td>
            
          </tr>
          
        </table>
        <input name="blogID" type="hidden" id="blogID" value="<?php echo $row_rsUpdate['blogID']; ?>">
        <input type="hidden" name="MM_update" value="editRecord">
    </form>
    
    
    </div> <!--end wrapper-->
    
    
    
    
    
    </body>
    </html>
    <?php
    mysql_free_result($rsUpdate);
    ?>

  5. #5
    Join Date
    Oct 2012
    Posts
    8
    Sorry for the delay in my response. Usually i get an email saying a post has been answered but not this time. Anyway, yes, it is writing all the data to the database except for the name of the file it is uploading. so the blogID, date, title, content all upload to the database. photo just comes up NULL. I have tried several techniques I got off the web but I don't have enough php understanding to apply it to my code.

  6. #6
    Join Date
    Jan 2009
    Posts
    3,346
    The name is included as part of the upload array...

    $_FILES['photo']['name']

  7. #7
    Join Date
    Oct 2012
    Posts
    8
    i don't know what that means and i don't know what to change. im not a total novice but I do rely on DW to write a lot of the PHP code. What am I supposed to change to make it work?

  8. #8
    Join Date
    Jan 2009
    Posts
    3,346
    Might be time to get some reading in...
    http://www.tizag.com/phpT/variable.php

  9. #9
    Join Date
    Oct 2012
    Posts
    8
    criterion9,
    I know what a variable is. I understand that. But you are coming at the problem from the mindset of a programmer, and I'm coming at it from the mind of an artist. Want me to show you how to be creative? Fine, here, I'll use your technique...'think differently'. There you go. I've helped you.

  10. #10
    Join Date
    Oct 2012
    Posts
    8
    okay, here is the 'upload a file and write to mySQL' code that I have been trying to fuse with my current code. My current code WORKS in the sense that it writes all the data (blogID, date, content, title) to the correct fields in the database. it does upload the file to the correct folder. id does NOT write the name of the uploaded file to the database.

    here is the code I've been trying to use (that i got from http://php.about.com/od/phpwithmysql...le_sql_3.htm):

    Code:
    <?php 
     
     //This is the directory where images will be saved 
     $target = "pix/"; 
     $target = $target . basename( $_FILES['photo']['name']); 
     
     //This gets all the other information from the form 
    
     $pic=($_FILES['photo']['name']); 
     
     
     //Writes the information to the database 
     mysql_query("INSERT INTO `base` VALUES ( '$pic')") ; 
     
     //Writes the photo to the server 
     if(move_uploaded_file($_FILES['photo']['tmp_name'], $target)) 
     { 
     
     //Tells you if its all ok 
     echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory"; 
     } 
     else { 
     
     //Gives and error if its not 
     echo "Sorry, there was a problem uploading your file."; 
     } 
     ?>
    when i apply this code, it still writes everything to the database EXCEPT the name of the uploaded file (and the uploaded file is still being uploaded properly).
    what am i missing?

  11. #11
    Join Date
    Oct 2012
    Posts
    8
    when i do 'echo $pic;' i get no result. so i take that as telling me that I am not filling those variables at all, which is strange because 'photo' definitly exists.
    Last edited by mightyhokie; 10-23-2012 at 09:41 AM.

  12. #12
    Join Date
    Jan 2009
    Posts
    3,346
    I see that you are utilizing the variable elsewhere:
    $target = $target . basename( $_FILES['photo']['name']);
    Is the file showing up in the folder with the correct name as expected?


    Looks like you need to add your name field into this query so it will update as expected as well as moving your upload check/name variable assignment above your query:
    $updateSQL = sprintf("UPDATE main SET title=%s, content=%s, photo=%s, `date`=%s WHERE blogID=%s",
    GetSQLValueString($_POST['title'], "text"),
    GetSQLValueString($_POST['content'], "text"),
    GetSQLValueString($_POST['photo'], "text"),
    GetSQLValueString($_POST['date'], "text"),
    GetSQLValueString($_POST['blogID'], "int"));

    Basically a very similar thing needs to happen based on your add script. You need to add the name field into your query and move your file upload/name variable assignment portion above the query so it can be included:
    $insertSQL = sprintf("INSERT INTO main (blogID, title, content, photo, `date`) VALUES (%s, %s, %s, %s, %s)",
    GetSQLValueString($_POST['blogID'], "int"),
    GetSQLValueString($_POST['title'], "text"),
    GetSQLValueString($_POST['content'], "text"),
    GetSQLValueString($_POST['photo'], "text"),
    GetSQLValueString($_POST['date'], "text"));

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles