Search code examples
phpmysqlstoring-data

PHP script store image to folder and path to MySQL database


I have a form in html which runs a php script whitch inserts text fields into a MySQL database. I use this database for creating user profiles but in the profiles i need also sound, video and pictures. Is there any script which creates a folder on the hardrive with the name i insert from the form and store the selected files in this folder and inserts the file path into the MySQL database?

Also i need to display them into a search result page and from the result page if i select a user i need to redirect me to a page wich displays the selected record whith it's own photos, sound, video and text as a profile page or something like this.

here is the form:

<form action="process.php" method="post" >
    <label>Όνομα:</label> <input type="text" name="Fname" /><br/><br/>
    <label>Επώνυμο:</label> <input type="text" name="Sname" /><br/><br/>
    <label>Είδος:</label> <input type="text" name="Genre" /><br/><br/>
    <label>Είδικότητα:</label> <input type="text" name="Specialty" /><br/><br/>
    <label>Βιογραφικό:</label> <input type="text" name="Bio" /><br/><br/>
    <input type="submit" value="Καταχώρηση"/>
</form>

and here is the script:

<?php
$con = mysql_connect("localhost","root","root");
if (!$con)
{
  die('Could not connect: ' . mysql_error());
}

mysql_select_db("fasma", $con);

$sql="INSERT INTO artists2 (Fname, Sname, Genre, Specialty, Bio)
VALUES
('$_POST[Fname]','$_POST[Sname]','$_POST[Genre]','$_POST[Specialty]','$_POST[Bio]')";

if (!mysql_query($sql,$con))
{
  die('Error: ' . mysql_error());
}
echo "Registration Successful";

mysql_close($con);
?>

Solution

  • When it comes to finding PHP functions, you should always check the PHP manual: http://php.net/manual/en/index.php

    It has great documentation on PHP's functions, including how to create folders/directories on your server.

    As for uploading and storing files, it's easier than you thnk: First, in your form, you need input fields of the type "file". For example:

    <label>Photo:</label> <input type="file" name="uploadImage" id="file" /><br/><br/>
    

    Once the form is submitted to process.php, this will upload the file to a temporary location on your server. In process.php, the file and the temporary location can be accessed like so:

    $_FILES["file"]["tmp_name"];
    

    You can then copy the file to any location on your server that you like. And since you are the one who decides where the file will be copied to, you can insert the file path into your database as you see fit.

    For more information, check out: http://www.w3schools.com/php/php_file_upload.asp