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!
Related
I want to upload 1000 images in just one click via URL. I have 1000 Image URLs stored in MYSQL database.
So please any one give me PHP code to upload that 1000 images via URL through mysql database.
Currently I am using the bellow code:-
It upload one image per click by posting URL of image...
But i want to upload 1000 image in one click by getting URLs from databse
$result = mysql_query("SELECT * FROM thumb") or die(mysql_error());
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
echo "<div>";
$oid = $row['tid'];
$th= $row['q'];
echo "</div>";
$thi = $th;
$get_url = $post["url"];
$url = trim('$get_url');
if($url){
$file = fopen($url,"rb");
$directory = "thumbnail/";
$valid_exts = array("php","jpeg","gif","png","doc","docx","jpg","html","asp","xml","JPEG","bmp");
$ext = end(explode(".",strtolower(basename($url))));
if(in_array($ext,$valid_exts)){
$filename = "$oid.$ext";
$newfile = fopen($directory . $filename, "wb");
if($newfile){
while(!feof($file)){
fwrite($newfile,fread($file,1024 * 8),1024 * 8);
}
echo 'File uploaded successfully';
echo '**$$**'.$filename;
}
else{
echo 'File does not exists';
}
}
else{
echo 'Invalid URL';
}
}
else{
echo 'Please enter the URL';
}
}
Thanks a lot.... …
The code you have is outdated and a lot more complex than needed. This is not a site where you get code because you ask, this is a learning environment.
I'll give you an example on which you can continue:
// Select the images (those we haven't done yet):
$sItems = mysql_query("SELECT id,url FROM thumb WHERE imported=0") or die(mysql_error());
// Loop through them:
while( $fItems = mysql_fetch_assoc($sItems) ){
$imgSource = file_get_contents($fItems['url']); // get the image
// Check if it didn't go wrong:
if( $imgSource!==false ){
// Which directory to put the file in:
$newLocation = $_SERVER['DOCUMENT_ROOT']."/Location/to/dir/";
// The name of the file:
$newFilename = basename($fItems['url'], $imgSource);
// Save on your server:
file_put_content($newLocation.$newFilename);
}
// Update the row in the DB. If something goes wrong, you don't have to do all of them again:
mysql_query("UPDATE thumb SET imported=1 WHERE id=".$fItems['id']." LIMIT 1") or die(mysql_error());
}
Relevant functions:
file_get_contents() - Get the content of the image
file_put_contents() - Place the content given in this function in a file specified
basename() - given an url, it gives you the filename only
Important:
You are using mysql_query. This is deprecated (should no longer be used), use PDO or mysqli instead
I suggest you make this work from the commandline and add an echo after the update so you can monitor progress
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'/>";
?>
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.
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
I'm trying to display an image along with other information from the database.
PHP
<?php
mysql_connect("localhost","111","222") or die("Could not connect to localhost");
mysql_select_db("movies") or die( "Could not connect to database");
$result = mysql_query("SELECT * FROM allmovies");
if ($result == false ) die(mysql_error());
while($row = mysql_fetch_array($result))
{
echo "<img src=' . $row['image'] . '>";
?>
Like:
Title: Blah
Price: Blah
Image: <img src=rarara">
All from MySQL in one page?
Don't store image data in a database, they are generally not suited to this and incurs extra overhead on your MySQL connections returning the data. You should be storing the path to the image file, and serving that.
If you insist on doing it you you should only be returning one image at a time with the proper header based on the image type using something like the following:
$imagedata = data_from_mysql();
header('Content-Length: ' . sizeof($imagedata) );
header('Content-Type: image/png');
echo $imagedata;
exit;
If you really want to make your page source bloated, slow, unmanageable, and nigh-uncacheable:
while( $imagedata = data_from_mysql() ) {
echo "<img src='data:image/png;base64," . base64_encode($imagedata) . "'>";
}
I cannot stress enough how these are terrible ideas that you should not use, but if you cannot listen to reason you can at least do bad things the right way.
You could use imagecreatefromstring()
$im = imagecreatefromstring($row['image']);
if ($im !== false) {
ob_start();
imagejpeg($im);
$data = ob_get_contents();
ob_end_clean();
echo '<img src="data:image/jpg;base64,' . base64_encode($data) . '" />';
}
Just my opinion, but it might be slightly more sane to save the images to the file server and then store a reference to the path instead of the whole image as a blob?