Can't display image from MySQL database in PHP - php

I have some problems here and I hope someone can help me. unfortunately I couldn't find a solution yet so you are my last hope.
I upload an image to my database but I cant display it. What I get is this icon when an image cant be find or load, but my database is full of pictures :-/
This is my PHP code:
<?php
$dbhost = "localhost";
$dbuser = "DBConnector";
$dbpassword = "root";
$db = "phplogin";
$b = $_POST['bildbestaetigen'];
if(isset($b)){
if(getimagesize($_FILES['bild']['tmp_name'])== FALSE)
{
echo "Choose a picture.";
}
else
{
$image= addslashes($_FILES['bild']['tmp_name']);
$name = addslashes($_FILES['bild']['name']);
$image= file_get_contents($image);
$image= base64_encode($image);
saveimage($name,$image);
}
}
displayimage();
function saveimage ($name,$image){
$link = mysqli_connect("localhost","root","") or die("Verbindung zur Datenbank konnte nicht hergestellt werden!");
mysqli_select_db($link,"phplogin") or die ("kann nich finden ");
$result= mysqli_query($link, "insert into bilder (name,bild) values ('".$name."','".$image."')");
if($result)
{
echo "Image uploaded";
}
else
{
echo "<br/> Image not uploaded";
}
}
function displayimage(){
$link = mysqli_connect("localhost","root","") or die("Verbindung zur Datenbank konnte nicht hergestellt werdengjghghghh");
mysqli_select_db($link,"phplogin") or die ("kann nich finden ");
$result = mysqli_query($link,"SELECT * from bilder");
while( $row = mysqli_fetch_array($result));
{
echo '<img height="300" width="300" src="data:bild;base64,'.$row[2].' ">';
}
mysqli_close($link);
}
?>
I tried so many things with out luck.
I hope someone can help me!

Use this W3Schools tutorial on PHP uploads. As mentioned in comments, save the image path in database, not file itself which may require the blob data type and can bloat your database very quickly.
To do so, upload the user-selected file from your HTML form onto your webserver as a physical file by specifying a target folder with $_FILES array (be sure folder exists) and using the move_uploaded_file() function:
$targetfile = "uploads/" .basename($_FILES['bild'])
...
# FILE VALIDATION
...
move_uploaded_file($_FILES['bild']['tmp_name'], $targetfile)
Then, save this image path (text string) into your database (assuming here bild is a text data type):
insert into bilder (name,bild) values ('".$name."','".$targetfile."')
Finally, just as you did before fetch records from the database table and echo the image path in src attribute of html's img tag (by the way filter the SQL query to particular user or image id as multiple records may output):
echo '<img height="300" width="300" src="'.$row[2].'">';
And remember the $targetfile variable will contain full, absolute path of image location.

Hi, assuming you have correctly uploaded an image into your database
and a folder somewhere inside your server. You can use this code to
print it out.
<?php
//codes to connect to database and mysql query to get image name from table inside database...
$target_dir = "uploads/"; //path of where the images are store on your server
$image_name = $row_image['image_name']; //name of the image retrieved by mysql query
//print the image
echo "<img src=" . "'" . $target_dir . "/" . $image_name . "'" . "style='width:50px;height:50px'/>";
?>

Related

php - cannot load image from database

I'm trying to design a page in php which shows images from database. or I would say only the location of images are in database.
But, when it shows up the images.. But it does print the image path.. That means it is getting the image path without any issue.
Here's my code:
<?php
$con = mysqli_connect("localhost", "root", "", "foodies");
if(mysqli_connect_errno()){
echo "Failed to connect to mysql";
mysqli_connect_error();
}
$sql = "select img, name from products";
$result = $con->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$img = $row["img"];
$name = $row["name"];
//$srcc = "C:\wamp\www\foodies\images";
//$quality=100;
//echo "id: " . $row["id"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. "<br>";
echo "<img src='".$row['img']."' width=200 height=200/>";
?>
I don't think you understand what's going on with the <img> tag. The src attribute needs to be a URL that tells your Web browser how to access the image, not a local file path. (URLs can be made for accessing local files, but that doesn't seem to be what you're doing, and that won't help you make Web-ready software anyway.)
The best way to display images from database is to save the image path in database tables then use Data URLS Schemes.
Try this instead:
<?php $con = mysqli_connect("localhost", "root", "", "foodies");
if(mysqli_connect_errno()){
echo "Failed to connect to mysql";
}
$sql = "select img, name from products";
$result = $con->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$img = $row["img"];
$name = $row["name"];
echo "<img src="data:image/jpeg;base64,<?php echo base64_encode( $img); ?>" width=200 height=200/>";
?>
The $img is the image file name, without the extension. Let's say you have saved your image in a folder "image" and the image file extension is jpeg.
I hope this is helpful.
while($row = mysql_fetch_array($result)) {
if($row['file_location']=="")
{
//your code
}
else
{
?>
VIEW IMAGE
<?php
}
}
Sorry for late reply to this. This was resolved. The issue was that I was giving location starting from root drive and not from root of web folder where the images were actually stored.
Ex: Website and images were located in C:\WAMP\my_site\images\
Instead of giving location from website root folder "\my_site\images\" I was giving it from C:\WAMP.......
Minor mistake though! ;)
Thank you everyone!

PHP QR Code Generator with SQL statement

I would like to use the results of a MYSQL query and generate a batch of QR Codes have the following php script via PhpQrCode. What I need is simply display the list of barcodes generated on HTML page. This is what I wrote so far:
<?php
include "qrlib.php";
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
while ($row = mysql_fetch_array($barcodes))
{
echo "<html>";
echo "<img src=";
QRcode::png ($row['Description']);
echo ">";
}
?>
The query is correct since I tested it out but I only get a blank page with a sort of broken image. Can someone help me as to what I am doing wrong please?
Thanks
SOLVED as follows:
<?php
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
//set it to writable location, a place for temp generated PNG files
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'label.png';
while ($row = mysql_fetch_array($barcodes))
{
$filename = $PNG_TEMP_DIR.'label'.$row['Description'].'.png';
QRcode::png($row['Description'], $filename);
echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo $filename;
}
?>
To render the image in the html page, hold the returned QRcode image in a location and then specify it as a link in src attribute of <img> tag.
If QRcode::png returns the raw image data, use data URIs to display:
$qr_code = base64_encode(QRcode::png ($row['Description']));
$src = 'data: image/png;base64,'.$qr_code;
echo '<img src="', $src, '">';
Solved as follows:
<?php
require "conf/config.php";
$con = mysql_connect(DBSERVER,DBUSER,DBPASS);
mysql_select_db(DBNAME, $con);
$barcodes = mysql_query( "SELECT Description FROM dbo_sensorsandparts ORDER BY ID ASC");
//set it to writable location, a place for temp generated PNG files
$PNG_TEMP_DIR = dirname(__FILE__).DIRECTORY_SEPARATOR.'temp'.DIRECTORY_SEPARATOR;
//html PNG location prefix
$PNG_WEB_DIR = 'temp/';
include "qrlib.php";
//ofcourse we need rights to create temp dir
if (!file_exists($PNG_TEMP_DIR))
mkdir($PNG_TEMP_DIR);
$filename = $PNG_TEMP_DIR.'label.png';
while ($row = mysql_fetch_array($barcodes))
{
$filename = $PNG_TEMP_DIR.'label'.$row['Description'].'.png';
QRcode::png($row['Description'], $filename);
echo '<img src="'.$PNG_WEB_DIR.basename($filename).'" /><hr/>';
echo $filename;
}
?>
I have stored the PNGs as files via variable $filename.

Insert and select from database

i've a problem with my query. The problem is that: the file is correctly loaded in the uploads folder. But not in the database with the content of the textarea.
i ve created this table into my database with:
CREATE TABLE dati(article VARCHAR(30), photo VARCHAR(30))
this is my code (pick from internet)
<?php
//This is the directory where images will be saved
$target = "../image/";
if(isset($_FILES['photo']['name'])) {
$target = $target . basename($_FILES['photo']['name']);
//This gets all the other information from the form
}
$article = (isset($_POST['article']));
$pic = (isset($_FILES['photo']['name']));
// Connects to your Database
//Writes the information to the database
if (isset($_FILES['photo']['name'])) if (isset($_POST['article'])) {
mysql_query("INSERT INTO nome_tabella (photo, article) VALUES ('{$_FILES['photo']['name']}', '{$_POST['article']}'");
}
//Writes the photo to the server
if(isset($_FILES['photo']['tmp_name']))
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
//Tells you if its all ok
echo "The file ". basename(isset($_FILES['uploadedfile']['name'])). " has been uploaded, and your information has been added to the directory";
}
else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
I tried several times, but does not insert data into the database. What's wrong?
This is the code for read the results
<?php
//Retrieves data from MySQL
$data = mysql_query("SELECT * FROM 'dati' (photo, article)") or die(mysql_error());
while($info = mysql_fetch_array( $data )) {
echo "<div id='cover'>";
echo "<img src='http://localhost/chiedifilm/image/".$info['photo']. "'>";
echo "</div>";
echo "" .$info['article']. "";
echo "<hr>"; } ?>
It does not load the image name and the textarea tinymce.
Im sorry for my bad english, i don't speak it very well.
Check your code:
//Writes the information to the database
if (isset($_FILES['photo']['name'])) if (isset($_POST['article'])) {
mysql_query("**NSERT** INTO nome_tabella (photo, article) VALUES ('{$_FILES['photo']['name']}', '{$_POST['article']}'");
}
where's "I" on INSERT statement
regards

How to upload an image on mysql database in PHP

I need a help to upload and show an image from a database in PHP, I created a database that name is students contains the ID, image size,and image name, is there is a way to do that?
I searched on youtube about this but I found this code, but this code save to a directory.
<?php
$name = $_FILES["myfile"] ["name"];
$type = $_FILES["myfile"] ["type"];
$size = $_FILES["myfile"] ["size"];
$temp = $_FILES["myfile"] ["tmp_name"];
$name = $size.$size .$name ;
$error = $_FILES["myfile"] ["error"];
if ($error > 0){
die ("Error uploading image");
}else{
move_uploaded_file($temp,"uploaded/".$name);
echo "Upload Completed";
}
?>
So, is there any way to save an image to a database and view it from a database?
You can save it into a MySQL table as a Blob but this isn't a really a good idea. Explanation here: http://www.hockinson.com/programmer-web-designer-denver-co-usa.php?s=47
Do what FDl said in the comments. Give each image a unique name and save it to your server, then save its unique name into your database.

Image is being save to the folder in db but other information is not being save

Need help above code is saving image to a folder(photos) define in the above code. but the other data which is being post by a form is not being save to database...I am new to php and i found this code from a website www.jeasyui.com. so i try to modified it but fail..as usual.:(
if (!isset($_FILES['image']['tmp_name'])) {
echo "";
}else{
$file=$_FILES['image']['tmp_name'];
$image= addslashes(file_get_contents($_FILES['image']['tmp_name']));
$image_name= addslashes($_FILES['image']['name']);
move_uploaded_file($_FILES["image"]["tmp_name"],"photos/" . $_FILES["image"]["name"]);
$location="photos/" . $_FILES["image"]["name"];
$name = $_REQUEST['prname'];
$code = $_REQUEST['prcode'];
$type = $_REQUEST['prtype'];
$weight = $_REQUEST['prweight'];
$desc = $_REQUEST['prdesc'];
$machine = $_REQUEST['prmachinemodel'];
include 'conn.php';
$sql = "insert into canon (product_name,product_code,product_type, product_descp, product_weight, machine_model, location) values('$name','$code','$type','$desc',$weight','$machine','$location')";
$result = #mysql_query($sql);
if ($result){
echo json_encode(array('success'=>true));
} else {
echo json_encode(array('msg'=>'Some errors occured.'));
}}?>
Use POST or GET instead REQUEST first of all.
Then what happens if you do a var_dump of the $sql, than try to execute it in phpMyAdmin ?
If you copied the code, then make sure you have html inputs with these names:prname,prcode,prtype,prweight,prdesc,prmachinemodel

Categories