Jump to content

[SOLVED] need a way to upload and view images inserted to database


contra10

Recommended Posts

ok i have this code that for some reason only inputs the data but can't read the image file

 

<?php 
mysql_connect("localhost", "root", "") or die(mysql_error()); 
mysql_select_db("registration") or die(mysql_error());

if(isset($_POST['upload']) && $_FILES['userfile']['size'] > 0)
{
$fileName = $_FILES['userfile']['name'];
$tmpName  = $_FILES['userfile']['tmp_name'];
$fileSize = $_FILES['userfile']['size'];
$fileType = $_FILES['userfile']['type'];

$fp      = fopen($tmpName, 'r');
$content = fread($fp, filesize($tmpName));
$content = mysql_real_escape_string($content);
fclose($fp);

if(!get_magic_quotes_gpc())
{
    $fileName = mysql_real_escape_string($fileName);
}


$query = "INSERT INTO image (name, size, type, content ) ".
"VALUES ('$fileName', '$fileSize', '$fileType', '$content')";

mysql_query($query) or die('Error, query failed'); 

echo "<br>File $fileName uploaded<br>";
} 


?>
</body> 
</html>

<table border="1" cellpadding="10">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data">
<table width="350" border="0" cellpadding="1" cellspacing="1" class="box">
<tr> 
<td width="246">
<input type="hidden" name="MAX_FILE_SIZE" value="2000000">
<input name="userfile" type="file" id="userfile"> 
</td>
<td width="80"><input name="upload" type="submit" class="box" id="upload" value=" Upload "></td>
</tr>
</form>
</table>

<?php
mysql_connect("localhost", "root", "") or die(mysql_error()); 
mysql_select_db("registration") or die(mysql_error());

$query  = "SELECT * FROM image WHERE id= '1'";
$result = mysql_query($query);

$row = mysql_fetch_assoc($result);

header("Content-type: image/gif");
echo($row['content']);
?>

 

instead i get

Ic„V^‰e–+QÙ$—]ò䥌c~ &‰>žYáUj¢d›•iœÒ¹$œíÙˆçŒ5äçŸ'¥¸'Zcý©PŒvê÷’Ÿi9(D¾æ£³æ(¥·å馂NÊ©„—~ ÒŽ‰Iª¨kþX)ª‡ÎD\©ŠÿÙ*¬ö9V¬¶Šd¦´Öºå½úåœPæªë°iUi,±:zÓ²Ç6;U°ÂéµÕ6È(´ÑZË-mÞ~›)‘âv‹l¹ã†‹.³ê®›l»îš)m¼•‰-öÒ[¯˜ú²ûk¿rÞë_Àý^K§Àå",®Âß2Ì­ÃÐB¼¬ÄÆRœ«Å¬bŒªÆ¬£Çl‚œ¦ÈäVh(ÉàŽº$DZºé/ÊwÆy+Ìûâ)Í//Ų‹áí\ãs>÷émA9tQÛ⌠G+íôÓPG-õÔTWmõÕXg­õÖ\wíõ×`‡-öØd—möÙh§­öÚl·íöÛpÇ-÷Üt×m÷Ýxç­÷Þ|÷Gí÷߀.øà„nøáˆ'®øâŒ7îøãG.ùä”Wnùå˜g®ùæœwîùç ‡.ú褗nú騧®úꬷîúë°Ç.ûìR;>GIF89aïü÷€€€€€€€€€€€€ÀÀÀÿÿÿÿÿÿÿÿÿÿÿÿ3f™Ìÿ3333f3™3Ì3ÿff3fff™fÌfÿ™™3™f™™™Ì™ÿÌÌ3ÌfÌ™ÌÌÌÿÿÿ3ÿfÿ™ÿÌÿÿ3333f3™3Ì3ÿ3333333f33™33Ì33ÿ3f3f33ff3f™3fÌ3fÿ3™3™33™f3™™3™Ì3™ÿ3Ì3Ì33Ìf3Ì™3ÌÌ3Ìÿ3ÿ3ÿ33ÿf3ÿ™3ÿÌ3ÿÿff3fff™fÌfÿf3f33f3ff3™f3Ìf3ÿffff3fffff™ffÌffÿf™f™3f™ff™™f™Ìf™ÿfÌfÌ3fÌffÌ™fÌÌfÌÿfÿfÿ3fÿffÿ™fÿÌfÿÿ™™3™f™™™Ì™ÿ™3™33™3f™3™™3Ì™3ÿ™f™f3™ff™f™™fÌ™fÿ™™™™3™™f™™™™™Ì™™ÿ™Ì™Ì3™Ìf™Ì™™ÌÌ™Ìÿ™ÿ™ÿ3™ÿf™ÿ™™ÿÌ™ÿÿÌÌ3ÌfÌ™ÌÌÌÿÌ3Ì33Ì3fÌ3™Ì3ÌÌ3ÿÌfÌf3ÌffÌf™ÌfÌÌfÿ̙̙3Ì™fÌ™™Ì™ÌÌ™ÿÌÌÌÌ3ÌÌfÌÌ™ÌÌÌÌÌÿÌÿÌÿ3ÌÿfÌÿ™ÌÿÌÌÿÿÿÿ3ÿfÿ™ÿÌÿÿÿ3ÿ33ÿ3fÿ3™ÿ3Ìÿ3ÿÿfÿf3ÿffÿf™ÿfÌÿfÿÿ™ÿ™3ÿ™fÿ™™ÿ™Ìÿ™ÿÿÌÿÌ3ÿÌfÿÌ™ÿÌÌÿÌÿÿÿÿÿ3ÿÿfÿÿ™ÿÿÌÿÿÿ!ù,ïüÿÿ H° Áƒ*\ˆÅ‡#JœH±¢Å‹3jœØp£Ç CŠI’bÇ’(Sª\É2¤C‡-cÊœISåËš8sêÜÉðLž@ƒ µ)ðçУH“V„iT©Ó§P}JµêP¦V³j¥ù³éÖ¯`]ô¶¬Y“cϪ]Ñ(Y¶p×6}·nعvóªÅ«·/X¯tý FJ6ðàÃ@ #^œT1ãÇACžœó­aʘIZÎÌ™%ÝËCcü,º´HÒ¦SoD­ºõÒž®c·…-»vBà m«¾œ[·iн}wÎ\xæÞÅOF®\vñäÍ?Þ:9tê}¡_ÇžW;wÑ×·ÿg»]üø½ÍŸ¿«Qýú¯êݿϾtòíG•Ÿ_¿Sþþe'V€võ×Bx ‚;-¸ ƒ•i!z#=8¡LZxaKj¸aJzøaI"Š8âiDH•‰R©‹,º˜‡2*c‹5u#Ž9F†a rdbBÙ`M;YP’1©äT89©¤”<>Ic„V^‰e–+QÙ$—]ò䥌c~ &‰>žYáUj¢d›•iœÒ¹$œíÙˆçŒ5äçŸ'¥¸'Zcý©PŒvê÷’Ÿi9(D¾æ£³æ(¥·å馂NÊ©„—~ ÒŽ‰Iª¨kþX)ª‡ÎD\©ŠÿÙ*¬ö9V¬¶Šd¦´Öºå½úåœPæªë°iUi,±:zÓ²Ç6;U°ÂéµÕ6È(´ÑZË-mÞ~›)‘âv‹l¹ã†‹.³ê®›l»îš)m¼•‰-öÒ[¯˜ú²ûk¿rÞë_Àý^K§Àå",®Âß2Ì­ÃÐB¼¬ÄÆRœ«Å¬bŒªÆ¬£Çl‚œ¦ÈäVh(ÉàŽº$DZºé/ÊwÆy+Ìûâ)Í//Ų‹áí\ãs>÷émA9tQÛ⌠G+íôÓPG-õÔTWmõÕXg­õÖ\wíõ×`‡-öØd—möÙh§­öÚl·íöÛpÇ-÷Üt×m÷Ýxç­÷Þ|÷Gí÷߀.øà„nøáˆ'®øâŒ7îøãG.ùä”Wnùå˜g®ùæœwîùç ‡.ú褗nú騧®úꬷîúë°Ç.ûìR; 

 

if u can please, please please tell me how to solve this or another way i can upload and view...I've tried all of the resource websites i can find and i get nowhere

Link to comment
Share on other sites

i guess im supposed to be looking at this?


$gotten = mysqli_query($link,"select * from pix order by pid desc limit 1");
if ($row = mysqli_fetch_assoc($gotten)) {
$title = htmlspecialchars($row[title]);
$bytes = $row[imgdata];
} else {
$errmsg = "There is no image in the database yet";
$title = "no database image available";
}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
header("Content-type: image/jpeg");
print $bytes;
exit ();
}
?>

 

which is in the comment

Link to comment
Share on other sites

ok i put this

<?php
mysql_connect("localhost", "root", "") or die(mysql_error()); 
mysql_select_db("registration") or die(mysql_error());

$gotten = mysql_query("select * from image WHERE id = '1'");
if ($row = mysql_fetch_assoc($gotten)) {
$title = htmlspecialchars($row[name]);
$bytes = $row[content];
} else {
$errmsg = "There is no image in the database yet";
$title = "no database image available";
}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
header("Content-type: image/gif");
print $bytes;
exit ();
}
?>

 

i didn't get any binary data but i didn't get any data at all

Link to comment
Share on other sites

for some reason still no image

<?php
mysql_connect("localhost", "root", "") or die(mysql_error()); 
mysql_select_db("registration") or die(mysql_error());

$gotten = mysql_query("select * from image WHERE id = '1'");
if ($row = mysql_fetch_assoc($gotten)) {
$title = htmlspecialchars($row['name']);
$bytes = $row['content'];
} else {
$errmsg = "There is no image in the database yet";
$title = "no database image available";
}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
header("Content-type: image/gif");
print ($bytes);
exit ();
}
?>

Link to comment
Share on other sites

btw im also checking the other script from the link on another page, for some reason i find that it uploads but i can't view it...lol...i guess bad luck i read the comments some people solved it but many people had the same problem

 

im not trying to confuse u but that code was

<?php

// Connect to database

$errmsg = "";
if (! @mysql_connect("localhost","root","")) {
        $errmsg = "Cannot connect to database";
        }
@mysql_select_db("registration");


// Insert any new image into database

if ($_REQUEST[completed] == 1) {
        // Need to add - check for large upload. Otherwise the code
        // will just duplicate old file ;-)
        // ALSO - note that latest.img must be public write and in a
        // live appliaction should be in another (safe!) directory.
        move_uploaded_file($_FILES['imagefile']['tmp_name'],"latest.img");
        $instr = fopen("latest.img","rb");
        $image = addslashes(fread($instr,filesize("latest.img")));
        if (strlen($instr) < 149000) {
                mysql_query ("insert into pix (title, imgdata) values (\"".
                $_REQUEST[whatsit].
                "\", \"".
                $image.
                "\")");
        } else {
                $errmsg = "Too large!";
        }
}

// Find out about latest image

$gotten = @mysql_query("select * from pix order by pid desc limit 1");
if ($row = @mysql_fetch_assoc($gotten)) {
        $title = htmlspecialchars($row[title]);
        $bytes = $row[imgdata];
} else {
        $errmsg = "There is no image in the database yet";
        $title = "no database image available";
        // Put up a picture of our training centre
        $instr = fopen("../wellimg/ctco.jpg","rb");
        $bytes = fread($instr,filesize("../wellimg/ctco.jpg"));
}

// If this is the image request, send out the image

if ($_REQUEST[gim] == 1) {
        header("Content-type: image/jpeg");
        print $bytes;
        exit ();
        }
?>

<html><head>
<title>Upload an image to a database</title>
<body bgcolor=white><h2>Here's the latest picture</h2>
<font color=red><?= $errmsg ?></font>
<center><img src=?gim=1 width=144><br>
<b><?= $title ?></center>
<hr>
<h2>Please upload a new picture and title</h2>
<form enctype=multipart/form-data method=post>
<input type=hidden name=MAX_FILE_SIZE value=150000>
<input type=hidden name=completed value=1>
Please choose an image to upload: <input type=file name=imagefile><br>
Please enter the title of that picture: <input name=whatsit><br>
then: <input type=submit></form><br>
<hr>
By Graham Ellis - graham@wellho.net
</body>
</html>

 

 

 

Link to comment
Share on other sites

it seems as if this code works ... thanks

 

files needed settings.php,install.php,index.php,insert.php, view.index.php

 

settings

<?php
// Create MySQL login values and 
// set them to your login information.
$username = "";
$password = "";
$host = "";
$database = "";

// Make the connect to MySQL or die
// and display an error.
$link = mysql_connect($host, $username, $password);
if (!$link) {
    die('Could not connect: ' . mysql_error());
}

$connect = mysql_select_db($database) or die("Can not select the database: ".mysql_error());
?>

 

install

<?php // Install table

include('settings.php');

$create_table = mysql_query("CREATE TABLE `tbl_images` (id tinyint(3) unsigned NOT NULL auto_increment, image blob NOT NULL, filetype varchar(25) NOT NULL, PRIMARY KEY (id))") or die('Unable to complete table installation" ' . mysql_error());

echo "Tables installed correctly";

?>

 

<?php include('settings.php'); ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<form enctype="multipart/form-data" action="insert.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
</body>
</html>

 

<?php
include('settings.php');
// Make sure the user actually 
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 
  
  // Temporary file name stored on the server
      $tmpName  = $_FILES['image']['tmp_name']; 
  $fileType = $_FILES['image']['type'];
      
  
  // Read the file 
      $fp   = fopen($tmpName, 'r');
      $data = fread($fp, filesize($tmpName));
      $data = addslashes($data);
      fclose($fp);
      

      // Create the query and insert
      // into our database.
      $query = "INSERT INTO `tbl_images` (`image`, `filetype`) VALUES ('" . $data . "', '" . $fileType . "')";
      $results = mysql_query($query) or die(mysql_error());
      
      // Print results
      print "Thank you, your file has been uploaded.";
      
  // GET LINK
  $data_query = mysql_query('SELECT `id` FROM `tbl_images` WHERE `image` = "' . $data . '" LIMIT 1') or die(mysql_error());
  $data = mysql_fetch_assoc($data_query);
  
  echo "<p>Click to view the image: <a href='view.php?id=" . $data['id'] . "'>Image " . $data['id'] . "</a>";
}
else {
   print "No image selected/uploaded";
}

// Close our MySQL Link
mysql_close($link);
?>  

 

view ir

<?php
include('settings.php');

$id = $_GET['id'];

if(!isset($id) || empty($id)){
die("Please select your image!");
}else{

$query = mysql_query('SELECT * FROM `tbl_images` WHERE `id`= "'.$id.'"');
$row = mysql_fetch_assoc($query);
$content = $row['image'];

header('Content-type: ' . $row['type'] .'');
print $content;

}

?>

Link to comment
Share on other sites

Can someone point out the fields I would need to modify here to use in my DB

I get this Unknown column 'filetype' in 'field list'

<?php
include('settings.php');
// Make sure the user actually 
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) { 
  
  // Temporary file name stored on the server
      $tmpName  = $_FILES['image']['tmp_name']; 
  $fileType = $_FILES['image']['type'];
      
  
  // Read the file 
      $fp   = fopen($tmpName, 'r');
      $data = fread($fp, filesize($tmpName));
      $data = addslashes($data);
      fclose($fp);
      

      // Create the query and insert
      // into our database.
      $query = "INSERT INTO `tbl_images` (`image`, `filetype`) VALUES ('" . $data . "', '" . $fileType . "')";
      $results = mysql_query($query) or die(mysql_error());
      
      // Print results
      print "Thank you, your file has been uploaded.";
      
  // GET LINK
  $data_query = mysql_query('SELECT `id` FROM `tbl_images` WHERE `image` = "' . $data . '" LIMIT 1') or die(mysql_error());
  $data = mysql_fetch_assoc($data_query);
  
  echo "<p>Click to view the image: <a href='view.php?id=" . $data['id'] . "'>Image " . $data['id'] . "</a>";
}
else {
   print "No image selected/uploaded";
}

// Close our MySQL Link
mysql_close($link);
?> 

 

 

Link to comment
Share on other sites

Last post worked out about field to change so never mind on that

New ?

Instead of renaming to image/type and using id to view can the upload file be rename to the value of another field in the form that the upload form field is in excample the form has a couple of fields Name, Address, phone No, and upload.

the person fills out the form and uploads the image in the code the uploaded file would get its new name from the Name field. then when ever that record is pulled up the image would be included on that record

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.