Displaying a MySQL table with blob images - php

I am only starting with PHP and as a part of exercise I wanted to design small website that allows you to upload image and then display all uploaded images
I got the image upload succesfully working and images are stored in database but I cant find the way to display images in table along with other data
$i=0;
while ($row = mysql_fetch_array($result))
{
echo '<td>'.mysql_result($result,$i,0).'</td>';
echo '<td>'.mysql_result($result,$i,1).'</td>';
echo '<td>'.mysql_result($result,$i,2).'</td>';
echo '<td>'.mysql_result($result,$i,3).'</td>';
echo '<td>'.base64_encode($result,$i,4).'</td>';
echo '<tr>';
$i++;
How to modify the code so the image is displayed?
this is code used to upload image
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'");
This is where I test it enter link description here
I was looking at Stack Overflow examples, but I couldn't find any that has the loop in it with data outputted into a table.

As you are starting with PHP, you should start with the right foot :)
Don't use mysql_* functions, these are deprecated. Instead, use mysqli_* or PDO
Storing images in the DB is "a bad idea", you better store the files in the file system (a-k.a. the HD) and reference the name to a field in the DB.
Instead of mysql_fetch_array, try with mysql_fetch_assoc so you can call the fields by name. i.e.: $row['db_field_name'];
About your problem, you will need a extra script to display the stored image. Something like this:
<?php
...
$row = mysql_fetch_assoc($result);
header("Content-type: image/jpeg"); //Set the correct image type.
echo $row['data'];
exit;
?>
And in your display html:
...
<img src="yourscript.php?image=XX" ...>
...
Hope this help :)

Related

error to upload to images with php

I am trying to upload two images with php. And add them to the database. Somehow it only uploads one image and the records in the database always have the same values.
this is the code i use
<?php
include "../connect.php";
$name1 = $_FILES['pic1']['name'];
$size1 = $_FILES['pic1']['size'];
$name2 = $_FILES['pic2']['name'];
$size3 = $_FILES['pic2']['size'];
if(isset($_POST['name']))
{
$extension1 = pathinfo($name1,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension1,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image1 = time().'.'.$extension1;
$file1 = "images/upload";
$pic1 = "$file1/".$new_image1;
move_uploaded_file($_FILES["pic1"]["tmp_name"],"../".$pic1."");
$insert = mysql_query("update temp set pic='$pic1' ") or die("error ins");
}
$extension2 = pathinfo($name2,PATHINFO_EXTENSION);
$array = array('png','gif','jpeg','jpg');
if (!in_array($extension2,$array)){
echo "<div class='faild'>".$array[0]."-".$array[1]."-".$array[2]."-".$array[3]." --> (".$name.")</div>";
}else if ($size>10000000){
echo "<div class='faild'>Size</div>";
}else {
$new_image2 = time().'.'.$extension2;
$file2 = "images/upload";
$pic2 = "$file2/".$new_image2;
move_uploaded_file($_FILES["pic2"]["tmp_name"],"../".$pic2."");
$insert = mysql_query("update temp set passport='$pic2'") or die("error ins");
}
}
?>
One of the problems you have is with your update statement. There is no 'where' statement saying which record in the database should be updated so this query updates them all. That's why you only have the last image in all the database rows.
Besides that, your code is not very good from a security point of view. You should take a look at mysqli or pdo for your database connection and queries because MySQL is deprecated and removed from PHP. Also take a look at SQL injections and data validation. Besides some very basic extension and size validation there is nothing there to keep things save. Try escaping and validating all user inputs.
And another point would be to take a look at 'functions'. You're running almost the exact same piece of code at least twice. And every code change has to be done twice. Perfect for a function call, something like
function storeImage($image){
// write the uploading and storing PHP here
}

getting jp2 images from mysql database and displaying in a web page using php

Iam unable to display jp2 image in web page.
This is main file to get image from database and display it in to web page.
In database images are in the format of JP2 image format.
<?php
echo' <html>';
echo'<body>';
echo' <table>';
echo' <tr><td>';
$dbcnx = #mysql_connect('127.0.0.1', 'root', 'root#19211');
if (!$dbcnx) {
die('<p>Unable to connect to the ' . 'database server at this time.</p>'
);
}
if (!#mysql_select_db('finaldb')) {
die('<p>Unable to locate the ' . 'database at this time.</p>');
}
$selectrc = 'select BPFT_Photo from photo_templates limit 1';
$result = #mysql_query($selectrc, $dbcnx);
if (!$result) {
die('<p>Error performing query: ' . mysql_error() . '</p>');
} else {
}
$n = mysql_num_rows($result);
$row = mysql_fetch_assoc($result);
$Photo_Details = $row['BPFT_Photo'];
$residentPhoto = getResidentPhoto();
$image_type_to_mime_type0 =image_type_to_mime_type($residentPhoto)
header('Content-type:$image_type_to_mime_type0');
echo' '.$residentPhoto;
echo'</td>';
echo'</tr>';
echo'</table>';
echo'</body>';
echo'</html>';
?>
jp2 image must supported in browser or you cant see..
and what method you used to add it in a webpage
(i think you used echo) .but echo will nothing do only write some charecters into a webpage
you must get image from database and save it in a temporary folder in server and echo the path to web
example :
$path="root/tmp/photo.jp2";
echo '<img src=$path>';
Remember that header() must be called before any actual output is sent
the above line comes from php.net.
You're using a header request, yet you already echoed some data so the headers already sent.
If you want to display JP2 data, you have 2 options:
Read the data from database, then create a temporary file (with say. file_put_contents, then load the image with an <img> tag.
Use the header(Content-type) method but outputing only the image data, without tables and other than JP2 raw data.
UPDATE:
Also look here about the very tiny support for JPEG-2000 format, after years and years. I would change my mind about JP2 usage on web if i were you..

delete an image file using php

I am building a forum with php and MySQL and I want to append current time to each image that users upload for their profile. I used time() function on each image file uploaded and it worked for the image file but I have trouble inserting the new filename into the database. I wanted to give each image a unique name to prevent override.
OK here is what I did: I stored the current time as $time and the filename in a variable, $photo and I tried to insert that variable’s value using $photo .= $time into the database so it has the filename as I did with each uploaded image. However the original filename is inserted into the database in every attempt.
Any workarounds?
$image = $_FILES['photo']['name'];
$time = time();
$image .= $time;
delete the existing photo
delete(image_dir/$row['current_photo.jpg']);
//does not work, but i want something like that
if(move_uploaded_file($_FILES['photo']['tmp_name'], 'image_dir/$image') {
$query = "INSERT INTO profile (user_id, profile_photo) VALUES($id, $image)";
mysqli_query($dbc, $query);
if(mysqli_affected_rows($dbc) == 1) {
echo "added to the database!";
}else {
echo "failed to add photo to the database";
}
}else {
echo "failed to upload photo";
}
how can i give the uploaded image unique the name since the original image name gets inserted in the database in every try i make?
i know the code looks funny :). just want to show the logic.
If you need a unique id, you can use the uniqid function
$name=uniqid();
you may need to use
$filename=uniqid();

The images from my database are appearing as little small question marks

// connects to database here
if(isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
$query = mysql_query("SELECT * FROM `blob` WHERE `id`='$id'");
$data = mysql_fetch_array($query);
header("content-type: image/jpeg");
echo $imageData;
}
else
{
echo "Error!";
}
<img src="showimage.php?id=1">
the images are then being shown through and image tag shown above but they just appear as small icons (the correct number for those listed in the database but not the actual image)
First, remove the <img src="showimage.php?id=1"> and put it on a different page; you can't keep it in the same page since it causes the web server to send headers before your script is even executed; your showimage.php should only contain PHP code, nothing else.
Then, change your code like this :
$data = mysql_fetch_array($query);
header("content-type: image/jpeg");
echo $data["image"];
I assume that your row is called "image" from your previous question.
Also, don't ask multiple questions for the same problem, you already got several answers on your previous question.

How to display through php an image stored in a folder considering that my image's link is stored in MySQL database

As good practice, I'm only storing my image's link in my database, the questios are:
How should I store my image's link? (let's say it's on c:)
c://image.jpg?
Which peace of PHP code should I use to display that image?
I'm only displaying the path, what should I do to display the image?
Can I use this:
$query = "SELECT ImageURL from WhateverTable";
$result = mysql_query($query) or die(mysql_error());
$Image = mysql_fetch_row($result);
echo "<img src='$Image[0]' alt='This is an image'>";
Thank you all lads
You only want to store the relative path, not the absolute path, as linking to something like
<img src="/var/www/vhosts/website.com/images/file.jpg">
would return a 404 on any real website. store your files in the database via a relative path (/images/file.jpg) or by only the filename if they are all in the same directory.
alternatively, you can learn MongoDB and it allows you to actually store files in the database itself.
I would strongly suggest that you use PDO instead.
Use relative URLs to your image folder in case you need to move them one day.
Here is an example.
// relative to your public webroot
$publicImageUrl = '/images/in/here';
// Pull up some record, maybe of a product
$select = 'SELECT imageFilename FROM products WHERE id = 2332';
$results = mysql_query($select);
if(!$results) {
// issue with query. deal with it here
} else {
if( mysql_num_rows($result) ) {
// record not found. deal with it here
}
$row = mysql_fetch_array($result);
$imageSrc = $publicImageUrl . '/' . $row['imageFilename'];
}
And then your HTML would be as follows
<img src="<?php echo $imageSrc; ?>" />
use PDO for php <-> mysql connection
post mysql query output

Categories