Tuesday, February 15, 2011

PHP/MySql : Store file path or name in database, file in folder.

Create a file : form.html

<form action=addmembers.php method=post enctype="multipart/form-data">
<table border="0" cellspacing="0" align=center cellpadding="3" bordercolor="#cccccc">
<tr>
<td>File:</td>
<td><input type="file" name="filep" size=45></td>
</tr>
<tr>
<td colspan=2><p align=center>
<input type=submit name=action value="Load">
</td>
</tr>
</table>
</form>


Create another file : addmembers.php
<?

if ($_POST["action"] == "Load")
{
$folder = "images/";



move_uploaded_file($_FILES["filep"]["tmp_name"] , "$folder".$_FILES["filep"]["name"]);

echo "<p align=center>File ".$_FILES["filep"]["name"]."loaded...";

$result = mysql_connect("localhost", "****", "****") or die ("Could not save image name Error: " . mysql_error());
mysql_select_db("test") or die("Could not select database");
mysql_query("INSERT into picture (URL) VALUES('".$_FILES['filep']['name']."')");

if($result) { echo "Image name saved into database"; }
else {

//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>


For Display the file use code :

<?
//Retrieves data from MySQL
mysql_connect("localhost", "****", "*****") or die ("Could not save image name Error: " . mysql_error());
mysql_select_db("test") or die("Could not select database");
$data = mysql_query("SELECT `URL` FROM picture ") or
die(mysql_error());
//Puts it into an array
$file_path = 'http://localhost/test/images/';

while($row = mysql_fetch_assoc( $data ))
{//Outputs the image and other data
$src=$file_path.$row['URL'];
echo "<img src=".$src.">  <br>";
}
?>


59 comments:

  1. hi,
    how to store the image in folder?

    ReplyDelete
    Replies
    1. Hi Utterly Anna use this
      $target_path="upload/";

      Delete
    2. it doesn't work! its showing in db but not in folder.

      Delete
    3. Its working fine, already tested and implemented. Check your folder permission or path.

      Delete
    4. Permission mean folder is writeable by web server (apache, nginx, etc).

      Delete
  2. its not storing the path into my database...
    table name: images
    table fields: url(1 field only)

    ReplyDelete
  3. First Check database connection if its correct. Check Field name and Database name.

    In above script:
    table name : picture
    table fields : URL

    ReplyDelete
    Replies
    1. how to upload the files into db and retreiving the file location and dipalying it on the webbrowser with mysqli and php

      Delete
    2. PHP script is same but you need to use mysqli() functions in place if mysql().
      For more information regarding mysqli() functions read this: http://goo.gl/zH4k7s

      Delete
  4. Thanks a mil! I've been searching the net for a script that will store file on server and display link to download it. I got it working now.

    Thanks.

    ReplyDelete
  5. Thanks but I was looking for something which can store Links in my database(like: http://www.avsysnepal.com/av.png)

    ReplyDelete
  6. it only works for pics how can i store videos

    ReplyDelete
  7. Try this may be helpful :-
    http://bytes.com/topic/php/answers/941830-how-upload-videos-database

    ReplyDelete
  8. Display the file use code not working also no error

    ReplyDelete
  9. i get broken files why is that?

    ReplyDelete
  10. @Dyyn Elaborate your problem in detail?

    ReplyDelete
  11. how ? to select one dropdown list store the image selected listed name folder.
    pls help me sir.

    ReplyDelete
  12. how to use ajax easy way in jquery.

    ReplyDelete
    Replies
    1. Try this :
      http://www.html.net/tutorials/javascript/lesson21.php
      http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_ajax_ajax

      Delete
  13. how can i store doc and pdf file, and view it in browser
    thankz in advance.

    ReplyDelete
    Replies
    1. You can store .doc and .pdf file using same method as mention above post.

      Delete
  14. The image has been stored in the folder. But the url is not storing in database !! why?

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Check below link for your reference.
      http://in2.php.net/pdo

      Delete
  16. Hi what do you name the tables in the database

    ReplyDelete
  17. hi jag, explain to me please and thanks for the notice..
    $uploadDir = 'images/';
    $fileName = $_FILES['Photo']['name'];
    $filePath = $uploadDir . $fileName;

    the query is --> INSERT INTO user_information (image) VALUES ('$filePath',);

    my question;
    the datatype for image is blob..is what im doing called saving URL in database and image in directory??bcse i've noticed in ur query that ur not including the directory..do explain please and thank u so much

    ReplyDelete
    Replies
    1. Datatype for Image field in above query is varchar for saving file name or path as a text.
      Its optional to include or exclude the directory path.

      Delete
  18. hi jag, explain to me please and thanks for the notice..
    $uploadDir = 'images/';
    $fileName = $_FILES['Photo']['name'];
    $filePath = $uploadDir . $fileName;

    the query is --> INSERT INTO user_information (image) VALUES ('$filePath',);

    my question;
    the datatype for image is blob..is what im doing called saving URL in database and image in directory??bcse i've noticed in ur query that ur not including the directory..do explain please and thank u so much

    ReplyDelete
  19. Good dy,

    Thanks for your code. It is working on my local machine which has a wamp server. However, it is not working on my real server.

    ReplyDelete
    Replies
    1. Need to check your real server configuration.

      Delete
  20. Hi, can you tell me if the following is applicable?
    when the user chooses an image from file input type, i want to rename it first (each product's image has the same name as the ID of the product) and then move it into a specific folder in order for me to retrieve it..

    storing images in mysql and then retrieving them using php didnt with work me, so i had to put all of the products' images in a folder and named each product's image by its ID

    ReplyDelete
    Replies
    1. $filename = basename($_FILES['file']['name']);
      $extension = pathinfo($filename, PATHINFO_EXTENSION);
      $Filenamee = "background.png";
      move_uploaded_file($_FILES["filep"]["tmp_name"] , "$folder"."$Filenamee".'.'.$extension);

      Delete
  21. thanks...this saved my life

    ReplyDelete
  22. THIS SAVED MY LIFE. OMG. THANK YOU SO MUCH :)

    ReplyDelete
  23. Hi,Can you please tell me how to validate the file uploaded.

    ReplyDelete
    Replies
    1. Try This :
      http://jagdeepmalhi.blogspot.in/2014/05/validation-uploaded-file-in-php.html

      Delete
  24. Thank you. very clear and easy to understand

    ReplyDelete
  25. sir ,this not saving file path in database,this is only saving file name. and my images are not saving in file folder

    ReplyDelete
  26. Can you please guide me how to disply the images into pdf from database and stored folder.

    ReplyDelete
    Replies
    1. You can use same code, but you need to work on how generate .pdf files using php.

      Delete
  27. hello can u please tel me how to do the same thing using code igniator??

    ReplyDelete
  28. Thats the perfect for Me Thanks

    ReplyDelete
  29. Hi,

    This is great however is it possible to give the file a unique name to prevent duplicates/overwriting?

    Thanks

    ReplyDelete
    Replies
    1. You could use something similar to this:


      ';
      echo mysqli_error($dbc);



      if (!empty($_FILES)) {

      $tempFile = $_FILES['file']['tmp_name']; // Generate a temporary file

      $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds; // Genrate a temporary file during the upload

      $targetFile = $targetPath. $name; // Set the location and the name for the uploaded file

      move_uploaded_file($tempFile,$targetFile); // Move the temporarary file the location defined above and rename it.

      $deleteFile = $targetPath.$old['avatar'];

      if($old['avatar'] != '') {

      if(!is_dir($deleteFile)) {


      unlink($deleteFile);

      }

      }

      }
      ?>

      Delete
    2. To avoid duplicate names simple solution use time stamp like:
      Example : move_uploaded_file($_FILES["filep"]["tmp_name"] , "$folder".time().$_FILES["filep"]["name"]);

      Delete
  30. hi i want to show the imagepath in edit option where imagepath is already in db i have to show that path while i selecting the id for edit.....

    ReplyDelete
  31. hi i want to show the imagepath in edit option where imagepath is already in db i have to show that path while i selecting the id for edit.....

    ReplyDelete
  32. hi sir
    Not able to save image or image path i created database test with table picture field url. still anything to change (changed localhost usernameand password)
    please help me

    ReplyDelete
  33. hi i inserted successfully, but while retrieving the image it just showing img box instead of real image please help me to solve this problem am using real server.

    ReplyDelete
  34. GOOOOOD JOOOOOOB! This Works! :)

    ReplyDelete
  35. Excellent…Amazing…. I’m satisfied to find so many helpful information here within the put up,for latest php jobs in hyderabad. we want work out extra strategies in this regard, thanks for sharing.

    ReplyDelete