Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6945481
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T13:26:30+00:00 2026-05-27T13:26:30+00:00

Using some examples I’ve found at ‘devarticles.com’ and ‘mistonline’ I’ve put together the script

  • 0

Using some examples I’ve found at ‘devarticles.com’ and ‘mistonline’ I’ve put together the script shown below that allows a user to save an image file to a mySQL database, saving the file as a BLOB.

<?php
$db_host = 'hostname'; 
$db_user = 'username';
$db_pwd = 'password';

$database = 'databasename';
$table = 'tablename';
// use the same name as SQL table


if (!mysql_connect($db_host, $db_user, $db_pwd))
    die("Can't connect to database");

if (!mysql_select_db($database))
    die("Can't select database");

// This function makes usage of
// $_GET, $_POST, etc... variables
// completly safe in SQL queries
function sql_safe($s)
{
    if (get_magic_quotes_gpc())
        $s = stripslashes($s);

    return mysql_real_escape_string($s);
}

// If user pressed submit in one of the forms
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
    // cleaning title field
    $title = trim(sql_safe($_POST['title']));

    if ($title == '') // if title is not set
        $title = '(empty title)';// use (empty title) string

    {
        if (isset($_FILES['photo']))
        {
            @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
            // Get image type.
            // We use @ to omit errors

            if ($imtype == 3) // cheking image type
                $ext="png";   // to use it later in HTTP headers
            elseif ($imtype == 2)
                $ext="jpeg";
            elseif ($imtype == 1)
                $ext="gif";
            else
                $msg = 'Error: unknown file format';

            if (!isset($msg)) // If there was no error
            {
                $data = file_get_contents($_FILES['photo']['tmp_name']);
                $data = mysql_real_escape_string($data);
                // Preparing data to be used in MySQL query

                mysql_query("INSERT INTO {$table}
                                SET ext='$ext', title='$title',
                                    data='$data'");

                $msg = 'Success: image uploaded';
            }
        }
        elseif (isset($_GET['title']))      // isset(..title) needed
            $msg = 'Error: file not loaded';// to make sure we've using
                                            // upload form, not form
                                            // for deletion

                if (isset($_POST['del'])) // If used selected some photo to delete
        {                         // in 'uploaded images form';
            $imageid = intval($_POST['del']);
            mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
            $msg = 'Photo deleted';
        }
        if (isset($_POST['view'])) // If used selected some photo to delete 
{ // in 'uploaded images form'; 
$imageid = intval($_POST['view']); 
mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid"); 
if(mysql_num_rows($result) == 1) 
{ 
$image = $row['myimage']; 
header("Content-type: image/gif"); // or whatever 
print $image; 
exit; 
} 
} 


    }
}
elseif (isset($_GET['show']))
{
    $imageid = intval($_GET['show']);

    $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
                             FROM {$table}
                            WHERE imageid=$imageid LIMIT 1");

    if (mysql_num_rows($result) == 0)
        die('no image');

    list($ext, $imagetime, $data) = mysql_fetch_row($result);

    $send_304 = false;
    if (php_sapi_name() == 'apache') {
        // if our web server is apache
        // we get check HTTP
        // If-Modified-Since header
        // and do not send image
        // if there is a cached version

        $ar = apache_request_headers();
        if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
            ($ar['If-Modified-Since'] != '') && // not empty
            (strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
            $send_304 = true;                                     // imagetime
    }

    if ($send_304)
    {
        // Sending 304 response to browser
        // "Browser, your cached version of image is OK
        // we're not sending anything new to you"
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);

        exit(); // bye-bye
    }

    // outputing HTTP headers
    header('Content-Length: '.strlen($data));
    header("Content-type: image/{$ext}");

    // outputing image
    echo $data;
    exit();
}
?>
<html><head>
<title>Save Photo(s) to Find</title>
</head>
<body>
<?php
if (isset($msg)) // this is special section for
                 // outputing message
{
?>
<p style="font-weight: bold;"><?=$msg?>
<br />
</p>
<?php
}
?>
<h1>Save Find images </h1>
<h2>Uploaded Find images:</h2>
<form action="<?=$PHP_SELF?>" method="post">
<!-- This form is used for image deletion -->

<?php
$result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
if (mysql_num_rows($result) == 0) // table is empty
    echo '<ul><li>No images loaded</li></ul>';
else
{
    echo '<ul>';
    while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
    {
        // outputing list
        echo "<li><input type='radio' name='del' title, value='{$imageid}'/>";
        echo "&nbsp;<small>{$title}</small>&nbsp;&nbsp";
        echo "<small>{$imagetime}</small></li>";
    }

    echo '</ul>';

    echo '<input type="submit" value="Delete selected"/>';

    echo "<input type=\"button\" value=\"View Photo\" onclick=\"location.href='<?=$PHP_SELF?>?show=1'\" />"; 
}
?>

</form>
<h2>Upload new Find image:</h2>
<form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
<label for="title"></label>
<label for="photo"></label>
<label for="password"></label>
<table border="0" cellpadding="0" cellspacing="0" bordercolor="#111111" width="38%">
  <tr>
    <td bgcolor="#FF9900" height="22" colspan="2"><p style="margin-left: 10"><b><font face="Verdana" size="2" color="#FFFFFF"> Upload a File</font></b></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB" colspan="2"><p style="margin-left: 10; margin-right: 10"><font face="Verdana" size="2"> <br>
      Please select a file from your local computer to upload to our web server 

      for saving in our database. This file can be of any type you like. Once you 

      have chosen a file, please click on the &quot;Upload this file&quot; button below.&nbsp;

      &nbsp;<br>
      &nbsp;</font></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> File Description:</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input type="text" name="title" id="title" size="64"/></td>
  </tr>
  <tr>
    <td bgcolor="#FFE3BB"><span style="margin-left: 10"><font face="Verdana" size="2">File Location:</font></span></td>
    <td bgcolor="#FFE3BB"><input type="file" name="photo" id="photo"/></td>
  </tr>
  <tr>
    <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> <br>
              <br>
      &nbsp;</font></td>
    <td width="66%" bgcolor="#FFE3BB"><input name="submit" type="submit" value="Upload This File"/></td>
  </tr>
</table>
<p>&nbsp;</p>
<p>&nbsp;</p>
</form>
</body>
</html>

I can save, list the files saved and delete the files from the database, but I’m having a problem in that I can’t work out how to retrieve and view the image, in fact my ‘View Photo’ deletes it.

I think that the answer lies within ‘Outputting List’ section, but I’ve tried all number of ways of trying the ‘View Photo’ button to execute the ‘View’ command.

I just wondered whether someone could perhaps take a look at this and let me know where I’m going wrong.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-27T13:26:30+00:00Added an answer on May 27, 2026 at 1:26 pm

    Here goes:

    <?php
    $db_host = 'localhost'; 
    $db_user = '';
    $db_pwd = '';
    
    $database = '';
    $table = 'images';
    // use the same name as SQL table
    
    if (!mysql_connect($db_host, $db_user, $db_pwd))
        die("Can't connect to database");
    
    if (!mysql_select_db($database))
        die("Can't select database");
    
    // This function makes usage of
    // $_GET, $_POST, etc... variables
    // completly safe in SQL queries
    function sql_safe($s)
    {
        if (get_magic_quotes_gpc())
            $s = stripslashes($s);
    
        return mysql_real_escape_string($s);
    }
    
    // If user pressed submit in one of the forms
    if ($_SERVER['REQUEST_METHOD'] == 'POST')
    {
        if (!isset($_POST["action"]))
        {
            // cleaning title field
            $title = trim(sql_safe($_POST['title']));
    
            if ($title == '') // if title is not set
                $title = '(empty title)';// use (empty title) string
    
            if (isset($_FILES['photo']))
            {
                @list(, , $imtype, ) = getimagesize($_FILES['photo']['tmp_name']);
                // Get image type.
                // We use @ to omit errors
    
                if ($imtype == 3) // cheking image type
                    $ext="png";   // to use it later in HTTP headers
                elseif ($imtype == 2)
                    $ext="jpeg";
                elseif ($imtype == 1)
                    $ext="gif";
                else
                    $msg = 'Error: unknown file format';
    
                if (!isset($msg)) // If there was no error
                {
                    $data = file_get_contents($_FILES['photo']['tmp_name']);
                    $data = mysql_real_escape_string($data);
                    // Preparing data to be used in MySQL query
    
                    mysql_query("INSERT INTO {$table}
                                    SET ext='$ext', title='$title',
                                        data='$data'");
    
                    $msg = 'Success: image uploaded';
                }
            }
            elseif (isset($_GET['title']))      // isset(..title) needed
                $msg = 'Error: file not loaded';// to make sure we've using
                                                // upload form, not form
                                                // for deletion
    
            if (isset($_POST['del'])) // If used selected some photo to delete
            {                         // in 'uploaded images form';
                $imageid = intval($_POST['del']);
                mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
                $msg = 'Photo deleted';
            }
    
            if (isset($_POST['view'])) // If used selected some photo to delete 
            { // in 'uploaded images form'; 
                $imageid = intval($_POST['view']); 
                mysql_query("SELECT ext, data FROM {$table} WHERE imageid=$imageid"); 
    
                if(mysql_num_rows($result) == 1) 
                { 
                    $image = $row['myimage']; 
                    header("Content-type: image/gif"); // or whatever 
                    print $image; 
                    exit; 
                } 
            } 
        }
        else
        {
            $imageid = intval($_POST['del']);
    
            if ($_POST["action"] == "view")
            {
                $result = mysql_query("SELECT ext, UNIX_TIMESTAMP(imagetime), data
                                         FROM {$table}
                                        WHERE imageid=$imageid LIMIT 1");
    
                if (mysql_num_rows($result) == 0)
                    die('no image');
    
                list($ext, $imagetime, $data) = mysql_fetch_row($result);
    
                $send_304 = false;
                if (php_sapi_name() == 'apache') {
                    // if our web server is apache
                    // we get check HTTP
                    // If-Modified-Since header
                    // and do not send image
                    // if there is a cached version
    
                    $ar = apache_request_headers();
                    if (isset($ar['If-Modified-Since']) && // If-Modified-Since should exists
                        ($ar['If-Modified-Since'] != '') && // not empty
                        (strtotime($ar['If-Modified-Since']) >= $imagetime)) // and grater than
                        $send_304 = true;                                     // imagetime
                }
    
                if ($send_304)
                {
                    // Sending 304 response to browser
                    // "Browser, your cached version of image is OK
                    // we're not sending anything new to you"
                    header('Last-Modified: '.gmdate('D, d M Y H:i:s', $ts).' GMT', true, 304);
    
                    exit(); // bye-bye
                }
    
                // outputing HTTP headers
                header('Content-Length: '.strlen($data));
                header("Content-type: image/{$ext}");
    
                // outputing image
                echo $data;
                exit();
            }
            else if ($_POST["action"] == "delete")
            {
                $imageid = intval($_POST['del']);
                mysql_query("DELETE FROM {$table} WHERE imageid=$imageid");
                $msg = 'Photo deleted';
            }
        }
    }
    ?>
    <html><head>
    <title>Save Photo(s) to Find</title>
    </head>
    <body>
    <?php
    if (isset($msg)) // this is special section for
                     // outputing message
    {
    ?>
    <p style="font-weight: bold;"><?=$msg?>
    <br />
    </p>
    <?php
    }
    ?>
    <h1>Save Find images </h1>
    <h2>Uploaded Find images:</h2>
    <form action="<?=$PHP_SELF?>" method="post">
    <!-- This form is used for image deletion -->
    
    <?php
    $result = mysql_query("SELECT imageid, imagetime, title FROM {$table} ORDER BY imageid DESC");
    if (mysql_num_rows($result) == 0) // table is empty
        echo '<ul><li>No images loaded</li></ul>';
    else
    {
        echo '<ul>';
        while(list($imageid, $imagetime, $title) = mysql_fetch_row($result))
        {
            // outputing list
            echo "<li><input type='radio' name='del' title, value='{$imageid}' />";
            echo "&nbsp;<small>{$title}</small>&nbsp;&nbsp";
            echo "<small>{$imagetime}</small></li>";
        }
    
        echo '</ul>';
    
        echo '<input type="submit" value="Delete selected" onclick="document.getElementById(\'action\').value=\'delete\'" />';
    
        echo '<input type="submit" value="View Photo" onclick="document.getElementById(\'action\').value=\'view\'" />';
    }
    ?>
        <input type="hidden" name="action" id="action" />
    </form>
    <h2>Upload new Find image:</h2>
    <form action="<?=$PHP_SELF?>" method="POST" enctype="multipart/form-data">
    <label for="title"></label>
    <label for="photo"></label>
    <label for="password"></label>
    <table border="0" cellpadding="0" cellspacing="0" bordercolor="#111111" width="38%">
      <tr>
        <td bgcolor="#FF9900" height="22" colspan="2"><p style="margin-left: 10"><b><font face="Verdana" size="2" color="#FFFFFF"> Upload a File</font></b></td>
      </tr>
      <tr>
        <td bgcolor="#FFE3BB" colspan="2"><p style="margin-left: 10; margin-right: 10"><font face="Verdana" size="2"> <br>
          Please select a file from your local computer to upload to our web server 
    
          for saving in our database. This file can be of any type you like. Once you 
    
          have chosen a file, please click on the &quot;Upload this file&quot; button below.&nbsp;
    
          &nbsp;<br>
          &nbsp;</font></td>
      </tr>
      <tr>
        <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> File Description:</font></td>
        <td width="66%" bgcolor="#FFE3BB"><input type="text" name="title" id="title" size="64"/></td>
      </tr>
      <tr>
        <td bgcolor="#FFE3BB"><span style="margin-left: 10"><font face="Verdana" size="2">File Location:</font></span></td>
        <td bgcolor="#FFE3BB"><input type="file" name="photo" id="photo"/></td>
      </tr>
      <tr>
        <td width="34%" bgcolor="#FFE3BB"><p style="margin-left: 10"><font face="Verdana" size="2"> <br>
                  <br>
          &nbsp;</font></td>
        <td width="66%" bgcolor="#FFE3BB"><input name="submit" type="submit" value="Upload This File"/></td>
      </tr>
    </table>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    </form>
    </body>
    </html>
    

    Hope it works for you!!

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I've seen some examples of C++ using template template parameters (that is templates which
I have seen some examples that after data is read using SqlCeResultSet that a
i've didn't found some examples to create NSPopover dynamically instead using the Interface Builder.
What are some examples of code that are not standards compliant when using visual
I've seen in some examples (e.g. [this][1][1]: http://www.ibm.com/developerworks/java/library/j-jsf2fu3/ ) that subcomponent can see attributes
I´ve been checking Microsot Unity IOC and found some examples using Code First approach.
I've heard something and seen some examples of web application built using ASP.NET /
What are some common , real world examples of using the Builder Pattern? What
I'm trying to write some microcontroller code using Texas Instruments examples, and it uses
I started using jQuery Mobile some time ago, and as those that know jQuery

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.