Acquisition of the image file from the database MySQL with the use of PHP

Extract the saved file of the image from the base

In the first article on this subject we discussed how to save the image in the database MySQL with the use of PHP. Now let’s consider how to extract the saved file of the image from the baseFor this we need to use two php files, the first is view_image.php:

// First of all, we need to check if the variable id is identified 
if (isset($_GET['id'])) {$id = $_GET['id'];}
    // Image file from the database is extracted with simple SQL query
    // Where $id is an image number 
    $result = mysql_query("SELECT * FROM images WHERE id='$id'",$db);

    ...

    // We use the function printf for code output 
    printf ("img class='work_image' src="https://site.softmaker.kz/files/span>'>", $myrow["id"]);
    // Then we transfer the parameter $myrow["id"] to the file get_image.php
?>

The second file is get_image.php:

// We need to send to browser the heading which informs that now the image file will be sent 
// First of all, we need to check if the variable id is identified
if ( isset( $_GET['id'] ) ) { // Here $id is an image number
    $id = $_GET['id'];
    // We perform query and get the file 
    $res = mysql_query("SELECT image FROM images WHERE id='$id'",$db);
    // Let’s check if there is at least one record 
    if ( mysql_num_rows( $res ) == 1 )
    {
        $image = mysql_fetch_array($res);
        // And we transfer the file itself
                    echo $image['image'];

}

 

} ?>

 As you see with the use of PHP there is nothing complicated in extraction of the file from the database. And sending of the file to user is done by one operator, however before the sending it is necessary to send the heading header(“Content-type: image/*”);, informing to browser that the transferred file is an image.

Attention! Transfer of headings is possible only until the first output of the information, if any information was sent to browser before the heading; for instance “echo ‘hello’;” in this case the transfer of the heading will result in error.