Saturday, September 4th, 2010

Upload and store files in Mysql using PHP : Part 2 – PHP file processing

To store uploaded files to MySQL database, you can use the normal INSERT statement as shown in the php example listed below:

<?php
  $con = mysql_connect("localhost", "", "");
  mysql_select_db("w3m");
  $error = $_FILES['w3img']['error'];
  $tmp_name = $_FILES['w3img']['tmp_name'];
  $size = $_FILES['w3img']['size'];
  $name = $_FILES['w3img']['name'];
  $type = $_FILES['w3img']['type'];
  print("\n");
  if ($error == UPLOAD_ERR_OK && $size > 0) {
    $fp = fopen($tmp_name, 'r');
    $content = fread($fp, $size);
    fclose($fp);     
    $content = addslashes($content);
    $sql = "INSERT INTO fyi_files (name, type, size, content)"
      . " VALUES ('$name', '$type', $size, '$content')";
    mysql_query($sql, $con);
    print("File stored.\n");
  } else {
    print("Database Save for upload failed.\n");
  }
  print("
\n");
  mysql_close($con);
?>

The addslashes() function is used to add backslashes to special characters that need to be escaped in SQL statements.

Share Article/Example:
  • DotNetKicks
  • DZone
  • StumbleUpon
  • Print
  • Add to favorites
  • Digg
  • del.icio.us
  • Twitter
  • Facebook
  • LinkedIn
  • Posterous
  • Slashdot

Tags: , , ,

Readers Comments (0)




Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.


Latest Additions

Popular User Submitted Links

1


Hosted & Optimized JS Libraries – Cached Commons

1


Multi-File Uploader & Resizer – Agile Uploader

1


Open source online notebook-to-do-list manager

1


3 tier app design in silverlight using azure & RIA services

1


Polymaps – A JS Library For Image & Vector-Tiled Maps

eXTReMe Tracker