Loading an image from a MySQL database with PHP - php

I have a question about loading an image from a MySQL database.
I have my database set up named 'demo' with one table 'contacts'. This has the 4 columns 'id', 'name', 'email' and 'image'. I can insert images with a HTML page I created. I also can achieve all my information with another HTML page I created, but the inserted BLOB images won't pop up, instead I see some huge bunch of characters (seems to besome encoding/decoding problem).
Heres the php-script that should get the data:
<?php
/*db information*/
$localhost="localhost";
$username="riko";
$password="QdTkCd12!";
$database="demo";
/*connect to database*/
mysql_connect($localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
/*prepare query*/
$query="SELECT * FROM contacts";
/*execute query*/
$result=mysql_query($query);
/*Number of rows delivered*/
$num=mysql_numrows($result);
/*Closing connection*/
mysql_close();
?>
<!-- Create a table to hold the data -->
<table border="1">
<tr>
<th>Image</th>
<th>Name</th>
<th>E-Mail</th>
</tr>
<?php
//Iterating over all rows in our table
$i=0;
while ($i < $num) {
//Get the first name, last name, mail and the image from the result
$first=mysql_result($result,$i,"first");
$last=mysql_result($result,$i,"last");
$email=mysql_result($result,$i,"email");
$data =mysql_result($result,$i,"image");
?>
<tr>
**HERE I WANT TO ECHO THE IMAGE INTO MY TABLE BUT I ONLY GET A BUNCH OF CHARACTERS**
<td><img src="<?php echo $data ?>" height="100" width="100"></td>
<td><font face="Arial, Helvetica, sans-serif"><?php echo $first." ".$last; ?></font></td>
<td><font face="Arial, Helvetica, sans-serif">E-Mail
</tr>
<?php
$i++;
}
?>
Can anyone tell me where my fault is? This is the php-script where I insert the images:
<?php
$localhost="localhost";
$username="riko";
$password="QdTkCd12!";
$database="demo";
$first=$_POST['first'];
$last=$_POST['last'];
$email=$_POST['email'];
mysql_connect($localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
// 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'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO contacts VALUES ('','$first','$last','$email', '$data')";
mysql_query($query);
mysql_close();
}
header("Location: connect.php");
die();
?>
I really don't know what's wrong here.

I think you need to prefix the value in the src attribute with content information:
echo '<img src="data:image/png;base64,' . $data . '" />';
Make sure the database blob field contains base64 encoded data.

Related

generate an Excel file using PHP

I'm new with PHP, I'm developping a WEB application that display a table with informations from an SQL server DATA BASE, the problem that I want to add a button to generate an EXCEL file that contains the table displayed? Is that possible??
#Ranjit this is the PHP code that displays the table and generate the excel file
edit 1
<?php
$ch="";
if(isset($_POST['historique']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$ch= "(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
?>
<table id="tab" border="1">
<tr>
<th><font color="red">Date</font></th>
<th><font color="red">Agent</font></th>
<th><font color="red">numéro</font></th>
</tr>
<?php
$search = " // my query
where operationDate between" .$ch;
$stmt = mssql_query($search);
while ($data = mssql_fetch_assoc($stmt))
{
?>
<tr>
<td><?php echo utf8_encode ($data['operationDate']);?></td>
<td><?php echo utf8_encode ($data['fullName']);?></td>
<td><?php echo utf8_encode ($data['number']);?></td>
</tr>
<?php
} }
?>
</table>
<?php
}
$output ='';
if(isset($_POST['excel']))
{
if ((!empty($_POST['Date_de_debut']))&& (!empty($_POST['Date_de_fin']))&&(!empty($_POST['Heure_de_debut']))&&(!empty($_POST['Heure_de_fin'])))
{
$rq = "// my query
where operationDate between" ."(CONVERT(Datetime, '".$_POST['Date_de_debut']." ".$_POST['Heure_de_debut'].".000',120)) and (CONVERT(Datetime, '".$_POST['Date_de_fin']." ".$_POST['Heure_de_fin'].".000',120))";
$res = mssql_query($rq);
if(mssql_num_rows($res)>0)
{
$output.='<table border=1>
<tr>
<th>Date</th>
<th>Depanneur</th>
<th>numéro</th>
</tr>
';
while ($row=mssql_fetch_array($res))
{
$output .='
<tr>
<td>'.$row["operationDate"].'</td>
<td>'.$row["fullName"].'</td>
<td>'.$row["number"].'</td>
</tr>';
}
$output .='</table>';
header("Content-Type: application/xls;charset=UTF-8");
header("Content-Disposition: attachement; filename=file.xls");
echo $output;
//mssql_close($conn);
}}}
?>
You'll have to select the data manually then insert them into the excel sheet, there's php library called PHPEXCEL you can use it.
See this
http://www.c-sharpcorner.com/article/export-to-excel-in-php-with-my-sql/
There are some nice packages out there to generate excel files such as
Box Spout and PHP Spreadsheet.
The documentation of both packages is very clear any you will be generating excel files within minutes of browsing through documentation.
Yes,
It is possible. You can follow this
1) Connect to database:
2) Define a filename of excel
//define separator (defines columns in excel & tabs in word)
$sep = "\t"; //tabbed character
$fp = fopen('database.xls', "w");
$schema_insert = "";
$schema_insert_rows = "";
//start of printing column names as names of MySQL fields
Sources - http://www.anillabs.com/2010/03/how-to-create-excel-file-with-mysql-data-using-php-code/

Uploading files to FTP using PHP

please, I really need your help. i have problems with uploading files to FTP server with using a PHP form. this form was o.k., but my hosting provider recently changed the version of PHP and from this moment, I have big problems. the communication with database is working, but file transfer not. please, can anyone advise me? thank you very much for your help!
the form:
<? include('./config.php'); ?>
<?
$spojeni = #MySQL_Connect($se, $uz, $he);
$db = #MySQL_Select_DB($DB);
?>
<FORM METHOD="POST" action="ins_info.php" enctype="multipart/form-data">
<TABLE>
<TR><TD><u><b>Upload a file:</b></u></TD></TR>
<TR>
<TD><b>Title:</b></TD>
<TD><INPUT TYPE="TEXT" NAME="titulek_form"></INPUT></TD>
</TR>
<TR>
<TD><b>Date:</b></TD>
<TD><INPUT TYPE="TEXT" NAME="datum_form"></INPUT></TD>
</TR>
<TR>
<TD><b>File:</b></TD>
<TD><INPUT TYPE="FILE" ACCEPT="*/*" SIZE="33" NAME="soubor"></INPUT></TD>
</TR>
<TR>
<TD><INPUT TYPE="SUBMIT" NAME="Odeslat" VALUE="Add to database"></INPUT></TD>
</TR>
</TABLE>
</FORM>
and the file ins_info.php: (the file from a form gets a new name, for example info1234.pdf -- but now is working only writing to a database -- the result is, that I get info1234. (without file on FTP and without filetype in a database)
<? include('./config.php') ?>
<?
#Set_Time_Limit(0);
$INI_ADMIN_PASSWORD = $_GET[INI_ADMIN_PASSWORD];
$INI_ftp_server = $_GET[INI_ftp_server];
$INI_info_path = $_GET[INI_info_path];
$INI_server_info_path = $_GET[INI_server_info_path];
$INI_server_tmp_path = $_GET[INI_server_tmp_path];
$INI_ftp_user = $_GET[INI_ftp_user];
$INI_ftp_pass = $_GET[INI_ftp_pass];
$spojeni_ftp = $_GET[spojeni_ftp];
$soubor = $_FILES["soubor"]["name"];
$titulek_form = $_POST["titulek_form"];
$datum_form = $_POST["datum_form"];
$DatumInt = $_POST["DatumInt"];
$MaxID = $_POST["MaxID"];
$prenos_info = $_POST["prenos_info"];
$vloz_info = $_POST["vloz_info"];
$jmeno = $_POST["jmeno"];
$vyber2 = $_POST["vyber2"];
$datum2 = $_POST["datum2"];
$nazev = $_POST["nazev"];
$soubor_name = $_POST["soubor_name"];
$cislo = $_POST["cislo"];
$jmeno = $_POST["jmeno"];*
IF($PASSWORD==$INI_ADMIN_PASSWORD):
$spojeni = #MySQL_Connect($se, $uz, $he);
$db = #MySQL_Select_DB($DB);
$vyber2 = #MySQL_Query("SELECT Max(ID) FROM info");
$MaxID = #MySQL_Result($vyber2, 0) +1;
$titulek_form = HTMLSpecialChars($titulek_form);
$datum_form = HTMLSpecialChars($datum_form);
$datum2 = Explode(".", $datum_form);
$DatumInt = MkTime(0,0,0, $datum2[1], $datum2[0], $datum2[2]);
$jmeno = "info";
$i = 1;
do
{
if($i==1) $jmeno_old = $jmeno;
$jmeno = $jmeno_old;
$nazev = Explode(".", $soubor_name);
SRand((double)MicroTime()*1e6);
$cislo = Rand (1, 9999);
// $nazev[0] .= $cislo;
$jmeno .= $cislo.".".$nazev[1];
$i++;
}
While(#File_Exists("$INI_info_path$jmeno"));
$vloz_info = #MySQL_Query("INSERT INTO info VALUES ('$MaxID', '$titulek_form', '$datum_form', '$jmeno', '$DatumInt')");
// *** FTP start
#chdir("$INI_server_tmp_path"); // docasny adresar
$spojeni_ftp = #ftp_connect("$INI_ftp_server"); // pripojeni k FTP serveru
#ftp_login($spojeni_ftp, "$INI_ftp_user", "$INI_ftp_pass"); // prihlaseni k FTP serveru
$prenos_info = #ftp_put($spojeni_ftp, "$INI_info_ftp_path$jmeno", "$soubor", FTP_BINARY); // kam se ma soubor ulozit
#chdir("$INI_server_home_path"); // nastaveni domovskeho adresare
#ftp_close($spojeni_ftp); // odhlaseni od FTP serveru
// *** FTP end
Header("Location: status.php?prenos_info=$prenos_info&vloz_info=$vloz_info");
?>
<?
ELSE:
Echo "<p>Error</b></p>";
ENDIF;
?>
folders have 777 rights. I'm be doubtful about POST and GET methods in the beginning of the file.

issue with blob image from mysql database

i have store an image into my database.
but i am unable to display the image what i have done till now is under.... any help will be appreciated. thanks in advance!
<?
$query="SELECT * from testimonial";
$ret = mysqli_query($mysql,$query);
if (isset($ret) && $ret->num_rows>0)
{
while($row=mysqli_fetch_array($ret))
{
$body=$row['body'];
$name=$row['name'];
$image=$row['img'];
?>
<li>
<div class="frame-icon"><? echo "<img src=test_img.php?id=".$row['id']." width=150 height=150/>";?></div>
<p class="quote"><?php echo $body; ?><span><?php echo $name; ?></span></p>
</li>
<?php }
echo "</table>";
}
?>
and my test_img code is
<?
<?php if (isset($_GET['id'])){
$id=mysql_real_escape_string($_GET['id']);
$query=mysql_query("SELECT *FROM testimonial WHERE id='$id' ");
while($row = mysql_fetch_assoc($query))
{
$image=$row["img"];
}
header("content-type: image/png");?>
hi Abhik i have try this one but i get something like this
and in my case i have png image so just change the jpeg to png the code you have given
but i got this <img src="data:image/png;base64,iVBORw0KGgpcMFwwXDANSUhEUlwwXDBcMGRcMFwwXDBkCAZcMFwwXDBw4pVUXDBcMFwwCXBIWXNcMFwwCxNcMFwwCxMBXDCanBhcMFwwCk9pQ0NQUGhvdG9zaG9wIElDQyBwcm9maWxlXDBcMHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHBcMBAIs2Qhc/0jAVww+H48PCtcIsAHvlwwAXjTCwhcMMBNm8AwHIf/D+pCmVxcAYCEAcB0kThLCIAUXDBAeo5CplwwQEYBgJ2YJlNcMKAEXDBgy2Ni41wwUC1cMGBcJ3/m01wwgJ34mXsBXDBblCEVAaCRXDAgE2WIRFwwaDtcMKzPVopFXDBY...6B2flQRKMpIP+DXCJ7HsLarL6Op8HdHo/cKIqsCFA4DsBDRQIS30pzU8aoX9JqqWYOntZjRPR6URKyCQVTCOGPXDDMiu8BWVM0P8z8cAzyOrJpdSgciP8+C8AX4VVUgLKOiHrSGqWC6QdFLGWnXDDsXCeivfHIulwiVdcZGHyV9mig3UVcMJKeKGdE9F/oUmo/Dlww+FmRXhaI6N+6UAzZjx8x875m3kOYV2AIXCJa34ViiLYU1XDWiO/o4jBEm9P9GoWpLFwwfUVV7o1CG/J8UW1nbUi5Qy85GdUkXCLPEtFzhQJcIlwiIFwiiMh1XCKyehwb863MfGHeNWQN25BDdoEyX4nB4+tmmtkUNHdwFxFRPxH93MymmNkxRPQGEf23mR0Xq82tfRqHXDDgpeiwnBj7tdvM2MzSVL5l7n+TmXcDWGdmvYWqy/FSWP3/Rkq7Q9AFpEtdQLqAdKkLyNig/xtcMETk0l30p0FqXDBcMFwwXDBJRU5ErkJggg==">
How about if you store the location of the image in DB then store the image itself in the file system? It's a better choice I think.
Proper way to display the blob images stored in DB is
echo '<img src="data:image/jpeg;base64,' . base64_encode($row['img']) . '">';

Unable to get the image from mysql DB

I'm new to php. I have a sample mysql db in that I have a table named testdb with columns id(INT) and image(BLOB). I have uploaded an image into testdb. Uploaded successfully. The following is the php code. The variable $conn contains the connection details. I have a html page which redirects to this php page on submitting.
<?php
$name = $_FILES["sample"]["name"];
echo $name . "<br/>";
$tmp_name = $_FILES["sample"]["tmp_name"];
echo $tmp_name . "<br/>";
$size = $_FILES["sample"]["size"];
echo $size . "<br/>";
$contents = file_get_contents($tmp_name);
$htmlen = htmlentities($contents);
$cont = mysql_real_escape_string($contents);
$query = "INSERT INTO testdb(image)
VALUES ('$cont')";
$dbquery = mysql_query($query, $conn);
if($dbquery){
echo "successfully inserted";
}
else{
echo "could not inserted" . mysql_error();
}
?>
I am trying to get the image with the following code. But it is showing string characters rather than the image. As far as I know this should work fine.
<?php
$query = "SELECT image, id
FROM testdb ";
$dbquery=mysql_query($query , $conn);
if(! $dbquery){
echo "Could not selected the data from database. " . mysql_error();
}
while( $row = mysql_fetch_array($dbquery) ){
$decodeimg = html_entity_decode($row["image"]);
echo "<img src= $decodeimg/><br/> hellow orld <br/>";
}
?>
Could anyone help me with this. Thanks in advance.
Instead of storing the actual image in your database (which is redundant because it is probably stored on your server too); why don't you just store the PATH to the image as a string, query the string from your db and then append it to the 'src' attribute with php.
I am also got the same error when show the BLOB image from DB. I just use the decoding method for this problem....
$photo=$myrow['image'];
echo '<img src="data:image/jpeg;base64,' . base64_encode( $photo ) . '" width="150" height="150" />

Getting an image from a database using PHP

first time using stack overflow.
I have followed the following 2 part youtube tutorial on uploading/storing an image in a MYSQL database. I have followed the instructions but my image is not appearing for me. I use connect.php to connect to the database, this appears to be working fine. It seems the problem is with get.php as when I test echoing any images from it I always get no image.
used phpmyadmin to create the database and am using xampp.
here is the link to the youtube tutorials
http://www.youtube.com/watch?v=CxY3FR9doHI
http://www.youtube.com/watch?v=vFZfJZ_WNC4&feature=fvwrel
Included are the files
<html>
<head>
<title>Upload an image</title>
</head>
<body>
<form action="index.php" method="POST" enctype="multipart/form-data">
File:
<input type="file" name="image"> <input type="submit" value="Upload">
</form>
<?php
include 'connect.php';
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file))
echo "Please select an image.";
else{
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name=addslashes($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if ($image_size==FALSE)
echo "That's not an image.";
else{
if(!$insert = mysql_query("INSERT INTO store VALUES('','$image_name','$image')"))
echo"Problem uploading image";
else{
$lastid = mysql_insert_id();
echo "image uploaded.<p />your image:<p /><img src=get.php?id=$lastid>";
}
}
}
?>
</body>
</html>
Here is get.php
<?php
include 'connect.php';
$id=stripslashes($_REQUEST('id'));
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image=$image('image');
header("content-type: image/jpeg");
?>
And finally connect
<?php
// connect to database
$db_host="localhost";
$db_username="root";
$db_pass="";
$db_name="test";
#mysql_connect("$db_host","$db_username","$db_pass") or die("Could not connect to mysql");
mysql_select_db("$db_name")or die("Cant find database");
?>
Your get.php doesn't echo $image.
Also $image=$image('image'); should be $image=$image['image'];, and $_REQUEST('id') should be $_REQUEST['id'].
P.S. Don't use addslashes to prevent against SQL injections. Use mysql_real_escape_string.
You never echo the image data in get.php, so you're serving a blank 0-byte image.
You are missing a line after the header output
header("content-type: image/jpeg");
echo $image;
Very quick glance, in get.php change:
$image=$image('image');
to
$image=$image['image'];
mysql_fetch_assoc() converts the results into an array.
You better of bas64_encoding an decoding that way none ansi chars wont create a problem.
base64_encode(file_get_contents($_FILES['image']['tmp_name']));
This is wrong as array is [] not ()
include 'connect.php';
$id=stripslashes($_REQUEST('id'));
$image = mysql_query("SELECT * FROM store WHERE id=$id");
$image = mysql_fetch_assoc($image);
$image=$image['image'];
header("content-type: image/jpeg");
echo base64_decode($image);
Piece of code I use in a site of mine:
<?php
ob_start();
require_once("db.php.lib");
DBLogin();
$sql = "select pic_user_id, pic_full_data as bindata, pic_full_mime as mime, pic_full_size as size from pics where pic_name = '".urldecode($_GET["pic_name"])."'";
$result = DBExec($sql);
if ($result)
{
$row = DBGetNextRow($result);
if ($row)
{
header("Content-type: ".$row["mime"]);
header("Content-length: ".$row["size"]);
ob_clean();
echo $row["bindata"];
ob_end_flush();
}
}
?>
It looks like you're leaving out the actual output of the image data, and the length might be required by some browsers...

Categories