A BETTER EXAMPLE WAS RECENTLY POSTED HERE:
How To Insert Images Into MySQL Database
<?php
/**
* At the end of this script, see the code for an external script called getimage.php
* along with examples of MySQL schema that you might use with this script.
* Configure a db connection below as: require_once('dbconn.php');
* Free for your personal use. A link back to www.hockinson.com would be appreciated.
*/
function get_cgi_var($name, $default_value = null)
{
// Nice work by Ondrej Jombik - http://www.nepto.org/
static $magic_quotes_gpc = null;
if ($magic_quotes_gpc === null) {
$magic_quotes_gpc = get_magic_quotes_gpc();
}
$var = @$_REQUEST["$name"];
if (isset($var)) {
if ($magic_quotes_gpc) {
if (is_array($var)) {
foreach (array_keys($var) as $key) {
$var[$key] = trim(stripslashes(strip_tags($var[$key])));
}
} else {
$var = trim(stripslashes(strip_tags($var)));
}
}
} else {
$var = @$default_value;
}
// return $var;
return @$_POST ? html_entity_decode($var, ENT_QUOTES) : $var;
};
function remove_temp_file($file_tmp)
{
if(file_exists($file_tmp)){
if(unlink($file_tmp)){ return true; }
}
return false;
}
$catid_array = array(
'100' => 'Foo',
'200' => 'Bar',
'300' => 'Toast',
'400' => 'Other'
);
$offset = 5;
$max_image_width = '550';
$max_image_height = '600';
$max_upload_bytes = '100000';
require_once('dbconn.php');
$self = basename($_SERVER['PHP_SELF']);
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-language" content="en-US">
<meta http-equiv="content-style-type" content="text/css">
<meta http-equiv="content-type" content="text/html; charset=us-ascii">
<meta name="robots" content="noindex, nofollow">
<meta http-equiv="Pragma" content="no-cache">
<meta name="expires" content="Fri, 01 Jan 1990 00:00:00 GMT">
<style type="text/css">
<!--
a{
color:#000000;
background-color:transparent;
}
body{
font-family:verdana,arial,helvetica,sans-serif;
font-size:11px;
}
form{
margin:0px;
}
input,select,textarea{
font-family:verdana,arial,helvetica,sans-serif;
font-size:11px;
}
td{
padding:5px;
}
input.hilite{
background-color:#ffff00;
color:#ff0000;
}
table{
background-color:#f0f8ff;
color:#000000;
}
-->
</style>
<title><?php echo $self; ?></title>
</head>
<body>
<p>Images for Shopping Cart (inventory1)</p>
<?php
switch($_SERVER['REQUEST_METHOD']){
Case 'POST':
$filename = $_FILES['myfile']['name'];
$file_err = $_FILES['myfile']['error'];
$file_tmp = $_FILES['myfile']['tmp_name'];
$filesize = $_FILES['myfile']['size'];
$filetype = $_FILES['myfile']['type'];
$file_ext = strrchr($filename, '.');
$delete = get_cgi_var('delete');
$id = get_cgi_var('id');
$item_name = get_cgi_var('item_name');
$submit = get_cgi_var('submit');
$errors = array();
if($id == ''){
$errors[] = 'No radio button was selected';
}
echo "\n".'<h3>Results ...</h3>';
echo "\n".'<table border="1" cellpadding="5" cellspacing="0">';
echo "\n".'<tr><td>';
if($submit == 'Upload Image'){
if($id == 'new_item'){
if($item_name == ''){
$errors[] = 'No Item name was entered';
}
}
if(file_exists($file_tmp) && list($image_width, $image_height, $image_type1, $img_attrib) = getimagesize($file_tmp) ){
if($image_width > $max_image_width){
$errors[] = 'The image width exceeds the allowed width of '.$max_image_width. ' pixels by '.($image_width-$max_image_width).' pixels';
}
if($image_height > $max_image_height){
$errors[] = 'The image height exceeds the allowed height of '.$max_image_height. ' pixels by '.($image_height-$max_image_height).' pixels';
}
if(!$data = addslashes(fread(fopen($file_tmp, "r"), filesize($file_tmp)))){
$errors[] = 'Unable to read file';
}
if(filesize($file_tmp) > $max_upload_bytes){
$errors[] = 'Image exceeds maximum file size of '.number_format($max_upload_bytes);
}
}else{
$errors[] = 'Unable to locate '.$file_tmp;
}
if(count($errors) > 0){
echo "\n".'<ol>';
for ($i = 0; $i < count($errors); $i++){
echo "\n".'<li>'.$errors[$i].'</li>';
}
echo "\n".'</ol>';
echo "\n".'</td></tr></table>';
echo "\n".'<p><a title="Image Upload" href="'.$self.'">Image Upload</a></p>';
echo "\n".'</body></html>';
remove_temp_file($file_tmp);
exit;
}else{
if($id == 'new_item'){
$qry = sprintf("INSERT INTO inventory1 (id, hidden, item_name, image, image_width, image_height, image_type1, image_type2, img_attrib)
VALUES ('%d', '%d', '%s', '%s', '%d', '%d', '%d', '%s', '%s')", '', '1', addslashes($item_name), $data, $image_width, $image_height, $image_type1, $filetype, addslashes($img_attrib));
$res = mysql_query($qry);
$insert_id = mysql_insert_ID();
if(mysql_affected_rows() == 0){
echo "\n".'<p>Query failed.<br>Query: '.$qry.'<br><br>'.mysql_error().'</p>';
}elseif(mysql_affected_rows() == 1){
echo "\n".'<p>'.$insert_id.' image uploaded</p>';
echo "\n".'<p><img src="getimage.php?id='.$insert_id.'"></p>';
}
}else{
$qry = sprintf("UPDATE inventory1
SET
image = '%s',
image_width = '%s',
image_height = '%s',
image_type1 = '%s',
image_type2 = '%s',
img_attrib = '%s'
WHERE id = '$id'",
$data, $image_width, $image_height, $image_type1, $filetype, addslashes($img_attrib));
mysql_query($qry);
$success = sprintf("Updated %d record\n", mysql_affected_rows());
if(!mysql_query("COMMIT")) {
echo "\n".'<p>Query failed.<br>Query: '.$qry.'<br><br>'.mysql_error().'</p>';
echo mysql_error() > 0 ? "\n".'<p>'.mysql_error().'</p>' : '';
}else{
echo "\n".'<p>'.$success.'</p>';
echo "\n".'<p><img src="getimage.php?id='.$id.'"></p>';
echo "\n".'<p>If no image appears,<br>then the upload failed.</p>';
}
}
remove_temp_file($file_tmp);
}
}elseif($delete == 'Delete Image'){
if($id == 'new_item'){
$errors[] = 'Invalid selection';
}
if(count($errors) > 0){
echo "\n".'<ol>';
for ($i = 0; $i < count($errors); $i++){
echo "\n".'<li>'.$errors[$i].'</li>';
}
echo "\n".'</ol>';
echo "\n".'</td></tr></table>';
echo "\n".'<p><a title="Image Upload" href="'.$self.'">Image Upload</a></p>';
echo "\n".'</body></html>';
exit;
}
$qry = sprintf("UPDATE inventory1 SET image = '%s', image_width = '%s', image_height = '%s', image_type1 = '%s', image_type2 = '%s', img_attrib = '%s' WHERE id = '$id'", '', '', '', '', '', '');
mysql_query($qry);
$success = sprintf("Deleted records: %d\n", mysql_affected_rows());
if(!mysql_query("COMMIT")) {
echo "\n".'<p>No image deleted. This record ID probably did not have an image.</p>';
}else{
echo "\n".'<p>'.$success.'</p>';
echo "\n".'<p>Image deleted.</p>';
}
}else{
echo "\n".'<p>Unknown submission.</p>';
}
echo "\n".'</td></tr></table>';
echo "\n".'<p><a title="Image Upload" href="'.$self.'">Image Upload</a></p>';
echo "\n".'</body></html>';
exit;
Case 'GET':
default:
?>
<form name="form1" method="POST" action="<?php echo $self; ?>" enctype="multipart/form-data">
<table border="1" cellpadding="5" cellspacing="0">
<tr>
<td>
<?php
$catid = get_cgi_var('catid');
$row_start = get_cgi_var('row_start');
$order = get_cgi_var('order');
$limit = get_cgi_var('limit');
$dir = get_cgi_var('dir');
if($row_start == ''){
$row_start = 0;
}
if($order == ''){
$order = 'id';
}
if($limit == ''){
$limit = $offset;
}
if($dir == ''){
$dir = 'ASC';
}
if($catid == ''){
$res = mysql_query('SELECT COUNT(*) FROM inventory1');
$record_count = $res > 0 ? mysql_result($res,0,0) : 0;
$qry = "SELECT id, item_name, image_width, image_height FROM inventory1 ORDER BY item_name LIMIT $row_start, $limit";
}else{
$res = mysql_query('SELECT COUNT(*) FROM inventory1 WHERE catid = "'.$catid.'"');
$record_count = $res > 0 ? mysql_result($res,0,0) : 0;
$qry = "SELECT id, catid, item_name, image_width, image_height FROM inventory1 WHERE catid = '$catid' ORDER BY item_name";
}
$res = mysql_query($qry);
$num_rows = mysql_num_rows($res);
if($res){
if($num_rows == 0) {
echo "\n".'<p>No records found</p>';
}else{
$i = 0;
echo "\n".'<table border="1" cellpadding="5" cellspacing="0">';
echo "\n".'<tr class="pme-row-1"><td class="pme-cell-0" colspan="5">Select a radio button, then Upload or Delete the associated image.<br>Maximum image size: '.$max_image_width.'x'.$max_image_height.' pixels<br>If the Width/Height columns are 0, no image is associated.</td></tr>';
echo "\n".'<tr class="pme-row-1"><td class="pme-cell-0">ID</td><td class="pme-cell-0">Item Name</td><td align="right" class="pme-cell-0">W</td><td align="right" class="pme-cell-0">H</td><td class="pme-cell-0"> </td></tr>';
while($ary = mysql_fetch_assoc($res)) {
while(list($key,$val) = each($ary)) {
$$key = htmlspecialchars(stripslashes(trim($val)));
}
if(strlen($item_name) > 255) {
$item_name = substr($item_name,0,25).'...';
}
if($image_width > 0) {
$display_image = '<img src="getimage.php?id='.$id.'" alt="'.$item_name.'" border="0" width="'.$image_width.'" height="'.$image_height.'">';
}else{
$display_image = ' ';
}
echo "\n".'<tr class="pme-row-0"><td class="pme-cell-1"><input type="radio" name="id" value="'.$id.'"></td><td class="pme-cell-1">'.$item_name.'</td><td align="right" class="pme-cell-1">'.$image_width.'</td><td align="right" class="pme-cell-1">'.$image_height.'</td><td class="pme-cell-1">'.$display_image.'</td></tr>';
}
echo "\n".'<tr class="pme-row-1"><td class="pme-cell-1"><input type="radio" name="id" value="new_item"></td><td class="pme-cell-1" colspan="4">Upload image for a new, hidden page</td></tr>';
echo "\n".'</table>';
if($record_count > $limit){
echo "\n".'<br><div> Pages ';
$page_count = intval($record_count / $limit);
if($record_count % $limit){ $page_count++; }
for($i = 1; $i<=$page_count; $i++){
$rs = $limit * ($i - 1);
echo $rs == $row_start ? $i : '<a title="Page '.$i.' of '.$page_count.'" href="'.$self.'?order='.$order.'&dir='.$dir.'&row_start='.$rs.'&limit='.$limit.'&offset='.$offset.'&catid='.$catid.'">'.$i.'</a>';
echo $i < $page_count ? ' - ' : ' ';
}
echo "\n".'</div><br>';
}
}
}else{
echo "\n".'<p>'.mysql_error().'<br>'.$qry.'</p>';
}
?>
</td>
<!-- Category Filter -->
<td rowspan="4" valign="top" style="padding:0px 0px 0px 10px">
<?php
$parts = array();
$qry2 = "SELECT DISTINCT catid FROM inventory1 ORDER BY catid";
$res2 = mysql_query($qry2);
while($row = mysql_fetch_array($res2, MYSQL_NUM)){
$parts[$row[0]] = $row[0];
}
foreach($catid_array as $key => $val){
echo in_array($key, $parts) ? "\n".'<a href="'.$self.'?catid='.$key.'">'.$val.'</a><br>' : '';
}
?>
<br><a href="<?php echo $self; ?>?catid=">All categories</a>
</td>
</tr>
<tr>
<td>
Item name (required for new uploads, max. 255 chars.)<br><br>
<input class="hilite" type="text" name="item_name" value="" size="69" maxlength="255">
</td>
</tr>
<tr>
<td>
Click the Browse button to locate the image file<br><br>
<input class="hilite" type="file" name="myfile" size="68">
</td>
</tr>
<tr>
<td>
<input type="hidden" name="MAX_FILE_SIZE" value="1000000">
<input type="submit" name="submit" value="Upload Image">
<!-- <input type="reset" name="submit" value="Reset Form"> -->
<input type="submit" name="delete" value="Delete Image">
</td>
</tr>
</table>
</form>
<p>
<?php echo $_SERVER['REQUEST_METHOD'] == 'POST' ? "\n".'<a title="Image Upload" href="'.$self.'">Image Upload</a> ' : ''; ?>
</p>
</body>
</html>
<?php
exit;
};
/*
Retrofitting images into existing table: `images1`
This assumes the `id` field already exists (see getimage.php).
ALTER TABLE `images1` ADD `image_caption` varchar(255) NOT NULL default '';
ALTER TABLE `images1` ADD `image` longblob NOT NULL;
ALTER TABLE `images1` ADD `image_width` smallint() NOT NULL default '0';
ALTER TABLE `images1` ADD `image_height` smallint() NOT NULL default '0';
ALTER TABLE `images1` ADD `image_type1` tinyint() NOT NULL default '0';
ALTER TABLE `images1` ADD `image_type2` varchar(20) NOT NULL default '';
ALTER TABLE `images1` ADD `img_attrib` varchar(30) NOT NULL default '';
ALTER TABLE `images1` ADD `hidden` tinyint() NOT NULL default '0';
ALTER TABLE `images1` ADD `updated` timestamp(14) NULL;
Sample MySQL schema for a PayPal shopping cart table:
CREATE TABLE `inventory1` (
`id` mediumint() unsigned NOT NULL auto_increment,
`item_name` varchar(255) NOT NULL default '',
`item_category` varchar(25) NOT NULL default '',
`catid` smallint() unsigned NOT NULL default '0',
`item_sub_cat` varchar(25) NOT NULL default '',
`scatid` smallint() unsigned NOT NULL default '0',
`item_number` varchar(20) NOT NULL default '',
`item_description` text NOT NULL,
`on0` varchar(25) NOT NULL default '',
`os0` varchar(255) NOT NULL default '',
`on1` varchar(25) NOT NULL default '',
`os1` varchar(255) NOT NULL default '',
`amount` float(10,2) NOT NULL default '0.00',
`weight` float(8,2) unsigned NOT NULL default '0.00',
`shipping1` float(8,2) NOT NULL default '0.00',
`shipping2` float(8,2) NOT NULL default '0.00',
`tax` float(6,2) NOT NULL default '0.00',
`taxable` tinyint() unsigned NOT NULL default '0',
`addx` smallint() unsigned NOT NULL default '1',
`currency_code` varchar(8) NOT NULL default 'USD',
`image` mediumblob NOT NULL,
`image_width` smallint() unsigned NOT NULL default '0',
`image_height` smallint() unsigned NOT NULL default '0',
`image_type1` tinyint() unsigned NOT NULL default '0',
`image_type2` varchar(20) NOT NULL default '',
`img_attrib` varchar(30) NOT NULL default '',
`hidden` tinyint() unsigned NOT NULL default '0',
`last_modified` timestamp(14) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `item_number_2` (`item_number`),
KEY `catid` (`catid`),
KEY `scatid` (`scatid`),
KEY `item_name` (`item_name`)
) TYPE=MyISAM;
// begin getimage.php
// configure or include a database connection here
$id = array_key_exists('id', @$_GET) ? @$_GET['id'] : '';
if(is_numeric($id)){
$data = '';
$type = '';
// database connection goes here
$res = @mysql_query('SELECT image, image_type2 FROM inventory1 WHERE id = '.$id);
$data = @mysql_result($res, 0, 'image');
$type = @mysql_result($res, 0, 'image_type2');
@header("Content-type: $type");
echo $data;
}
// end getimage.php
*/
?>