How to Upload an Image to PHP With MySQL Insert

Written by kile mckenna
  • Share
  • Tweet
  • Share
  • Pin
  • Email
How to Upload an Image to PHP With MySQL Insert
PHP and MySQL can combine to upload photo-related information to a database. (Comstock Images/Comstock/Getty Images)

PHP scripts often are paired with a MySQL database to generate content on a website. In the case of a photo gallery, the images themselves reside in a folder on a server, and the photo information, perhaps the photo's file name, a caption and a photo ID number, is stored in the MySQL database. Uploading a photo requires placing the photo in the correct folder and creating an SQL "Insert" query to place the image's information in the database. Use PHP script to accomplish both of these moves.

Skill level:
Easy

Other People Are Reading

Instructions

  1. 1

    Create a form in the body of an HTML document that can upload a file and accept user input for a "caption" and "photo_id" number. Give the "Submit" button the name attribute of "upload." When the user clicks the form, a superglobal $_POST array will be created that includes all the name attributes of the form.

    <form action="" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">

    <p>

    <label for="image">Upload photo:</label>

    <input type="file" name="image" id="image" />

    </p>

    <p>

    <label for="textfield">Caption:</label><textarea name="caption" cols="40" rows="4" id="caption" maxlength="200" onkeyup="return ismaxlength(this)"></textarea></p>

    </label>

    </p>

    <p>

    <label for="photo_id">Image order:</label>

    <input name="photo_id" type="text" id="photo_id" />

    </p>

    <p>

    <input type="submit" name="upload" id="upload" value="Upload" />

    </p>

    </form>

  2. 2

    Begin your PHP code at the top of your HTML document and test for the existence of the "upload" element in the $_POST array. Its existence will trigger your PHP code to run.

    <?php

    if (array_key_exists('upload',$_POST)) {

  3. 3

    Create a connection to your MySQL server and a database called "sample." Use your own database user name and password in place of the "username" and "password."

    $conn = new mysqli('localhost','username','password','sample') or die ("error");

  4. 4

    Create a table called "gallery" within the "sample" database and set it up with three columns labelled "filename," "caption" and "photo_id."

    $query = "CREATE TABLE IF NOT EXISTS gallery

    (

    filename varchar(30) NOT NULL,

    caption varchar (500) NOT NULL,

    photo_id int (3) NOT NULL

    )";

    $result = mysqli_query($con,$query);

  5. 5

    Add PHP code to define an upload directory called "images." Create a folder called "images" in the same location where you are saving your document. Change the permissions on the folder to read and write access. In Windows, right-click the folder and select the "Security" tab. Place a check mark next to "Read" and "Write." On a Mac, press "Command" and "I" and scroll to "Ownership and Permissions" under "Details." Change the setting for "Others" to "Read/Write." The PHP code is:

    define('UPLOAD_DIR', 'images/');

  6. 6

    Add PHP code to move the photo and assign the file's name to the $file variable.

    move_uploaded_file($_FILES['image']['tmp_name'],UPLOAD_DIR.$_FILES['image']['name']);

    $file = $_FILES['image']['name'];

  7. 7

    Add your MySQL "Insert" query to enter the photo information into the database. Set a variable called $OK to true if the "Insert" query is successful.

    $sql3 = "INSERT INTO gallery (filename, caption, photo_id) VALUES('$file', ?, ?)";

    $stmt = $conn->stmt_init();

    if ($stmt->prepare($sql3)) {

    $stmt-&gt;bind_param('ss', $_POST['caption'], $_POST['photo_id']);
    
    $OK = $stmt-&gt;execute();
    
  8. 8

    Add a display message to indicate success if the $OK variable is set to true. Otherwise, display an error message. Close your PHP coding:

    if ($OK) {

    echo ("You're photo has been uploaded successfully"); }

    else {

    echo $response = $stmt->error;

    }

    }

    ?>

  9. 9

    Save your page with a .php extension to your PHP server or a PHP code emulator online. You should see a familiar upload form. Choose a small photo on your desktop, add a sample caption and photo ID number and push "Submit." You should receive a message at the top of the page in the browser that your photo has been uploaded successfully. Check your database for a new table called "gallery" with the information you submitted in the form. The full code appears as follows:

    <?php

    if (array_key_exists('upload',$_POST)) {

    $conn = new mysqli('localhost','username','password','sample') or die ("error");

    $query = "CREATE TABLE IF NOT EXISTS gallery

    (

    filename varchar(30) NOT NULL,

    caption varchar (500) NOT NULL,

    photo_id int (3) NOT NULL

    )";

    $result = mysqli_query($con,$query);

    define('UPLOAD_DIR', 'images/');

    move_uploaded_file($_FILES['image']['tmp_name'],UPLOAD_DIR.$_FILES['image']['name']);

    $file = $_FILES['image']['name'];

    $sql3 = "INSERT INTO gallery (filename, caption, photo_id) VALUES('$file', ?, ?)";

    $stmt = $conn->stmt_init();

    if ($stmt->prepare($sql3)) {

    $stmt-&gt;bind_param('ss', $_POST['caption'], $_POST['photo_id']);
    
    $OK = $stmt-&gt;execute();
    
    }
    

    if ($OK) {

    echo ("You're photo has been uploaded successfully"); }

    else {

    echo $response = $stmt->error;

    }

    }

    ?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <html">

    <head>

    </head>

    <body>

    <form action="" method="post" enctype="multipart/form-data" name="uploadImage" id="uploadImage">

    <p>

    <label for="image">Upload photo:</label>

    <input type="file" name="image" id="image" />

    </p>

    <p>

    <label for="textfield">Caption:</label><textarea name="caption" cols="40" rows="4" id="caption" maxlength="200" onkeyup="return ismaxlength(this)"></textarea></p>

    </label>

    </p>

    <p>

    <label for="photo_id">Image order:</label>

    <input name="photo_id" type="text" id="photo_id" />

    </p>

    <p>

    <input type="submit" name="upload" id="upload" value="Upload" />

    </p>

    </form>

    </body>

    </html>

Don't Miss

Filter:
  • All types
  • Articles
  • Slideshows
  • Videos
Sort:
  • Most relevant
  • Most popular
  • Most recent

No articles available

No slideshows available

No videos available

By using the eHow.co.uk site, you consent to the use of cookies. For more information, please see our Cookie policy.