I've read almost all topics related to this. i dont know whats causing it.
This is code for showing images
<html>
<body>
<?php
mysql_connect('localhost','root','') or die("Unable to Connect: ".mysql_error());
mysql_select_db("punjabi") or die("Unable to Select Database: ".mysql_error());
$sql = "SELECT imagename, mimetype, imagedata
FROM images WHERE ID = 1";
$result = #mysql_query($sql);
if(!$result)
{
die(mysql_error());
}
$file = mysql_fetch_array($result);
$imagename = $file['imagename'];
$mimetype = $file['mimetype'];
$imagedata = $file['imagedata'];
header("content-type: $mimetype");
echo($imagedata);
?>
This is the code for inserting images
<!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>Add Post</title>
<style type="text/css">
*
{
margin:0px;
padding:0px;
}
</style>
</head>
<body bgcolor="#333333">
<?php if(isset($_POST['submit'])):
{
if (!is_uploaded_file($_FILES['uploadfile']['tmp_name']))
{
die("$uploadfile is not an uploaded file!");
}
$uploadfile = $_FILES['uploadfile']['tmp_name'];
$uploadname = $_FILES['uploadfile']['name'];
$uploadtype = $_FILES['uploadfile']['type'];
$uploaddesc = $_POST['desc'];
$tempfile = fopen($uploadfile,'rb');
$filedata = fread($tempfile,filesize($uploadfile));
$filedata = addslashes($filedata);
$sql = "INSERT INTO images SET
imagename = '$uploadname',
mimetype = '$uploadtype',
description = '$uploaddesc',
imagedata = '$filedata'";
$ok = #mysql_query($sql);
if (!$ok) die("Database error storing file: " .mysql_error());
$sql = "Select id from images where imagename = '$uploadname'";
$result = #mysql_query($sql);
if(!$result) die(mysql_error());
if(mysql_num_rows($result)!=1) die(mysql_error());
$row = mysql_fetch_array($result);
$imageid = $row['id'];
$title = $_POST['title'];
$content = $_POST['content'];
$sql = "INSERT into posts SET
title = '$title',
content = '$content',
imageid = '$imageid'";
if(!#mysql_query($sql))
{
die(mysql_error());
}
header("Location:http://localhost/punjabi/adminhome.php");
}
?>
<?php else: ?>
<div id="post">
<form action="<?php echo($_SERVER['PHP_SELF']) ?>" method="post" enctype="multipart/form-data" >
Title: <input type="text" name="title" /><br /><br /><br />
Content:<br /> <textarea cols=100 rows="40" wrap="hard" name="content" /></textarea><br /><br />
Image: <input type="file" name="uploadfile" /><br /><br />
Image Desc: <input type="text" name="desc" /><br /><br />
<input type="submit" value="Submit" name="submit" />
</form>
</div>
<?php endif; ?>
</body>
</html>
And This is the Table Structure:
CREATE TABLE filestore (
-> ID INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
-> FileName VARCHAR(255) NOT NULL,
-> MimeType VARCHAR(50) NOT NULL,
-> Description VARCHAR(255) NOT NULL,
-> FileData MEDIUMBLOB
->);
And Help would be appreciated!
The problem is that the headers have already been sent when you do:
<html>
<body>
<?php
So you cannot set the header for the image anymore:
header("content-type: $mimetype");
Just getting rid of the html (an image is not html / text) before the php tag should solve that.
Related
Getting this error over and over.
I changed some things, but it still wont work.
Basically its a simple News system, where you can insert title, text and a Document to the database.
title and text getting inserted to the database, but the image_name and location not.
Also here the Database:
CREATE TABLE "news" (
"ID" INTEGER UNIQUE,
"TITEL" TEXT,
"NEWS" TEXT,
"CREATED_AT" TEXT,
"image_name" TEXT,
"location" TEXT, PRIMARY KEY("ID" AUTOINCREMENT) );
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>News hinzufügen</title>
</head>
<body>
<?php
if(isset($_POST["submit"])){
require("mysql.php");
//conc
$stmt = $mysql->prepare("INSERT INTO news (TITEL, NEWS, CREATED_AT) VALUES (:titel, :news, :now)");
// Titel, TXT
$stmt->bindParam(":titel", $_POST["titel"], PDO::PARAM_STR);
$stmt->bindParam(":news", $_POST["news"], PDO::PARAM_STR);
//Files
$file_name = $_FILES['image']['name'];
$file_temp = $_FILES['image']['tmp_name'];
$exp = explode(".", $file_name);
$ext = end($exp);
$image = "news".'.'.$ext;
$ext_allowed = array("pdf");
$location = "uploads/".$image;
if(in_array($ext, $ext_allowed))
{
if(move_uploaded_file($file_temp, $location))
{
$mysql="INSERT INTO `news` (image_name, location) VALUES('$image', '$location')";
$mysql->exec($query); <----- ERROR LINE
echo "<script>alert('Image uploaded!')</script>";
echo "<script>window.location='addnews.php'</script>";
}
}
else
{
echo "<script>alert('Only image to upload!')</script>";
echo "<script>window.location='addnews.php'</script>";
}
// Time
$now = time();
$stmt->bindParam(":now", $now, PDO::PARAM_STR);
$stmt->execute();
echo "Die News wurde erfolgreich hinzugefügt.";
}
?>
<form action="addnews.php" method="post" enctype="multipart/form-data">
<input type="text" name="titel" placeholder="Titel" required><br>
<textarea name="news" cols="30" rows="10"></textarea><br>
<input type="file"name="image" required="required" />
<br>
<br>
<button type="submit" name="submit">Hinzufügen</button><br>
</form>
</body>
</html>
Try this:
$query = "INSERT INTO `news`
(image_name, location)
VALUES
('$image', '$location')";
$mysql->exec($query);
Im working usign PDO and PHP.
This is my table in Postgre
CREATE TABLE public.img
(
id integer NOT NULL DEFAULT nextval('img_id_seq'::regclass),
nombre bytea
)
When i store the file data i use this method
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
if(isset($_POST["insert"]))
{
$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO img (nombre) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $file);
$ISp_Res->execute();
}
?>
And in the table the values are
ID nombre
4; "\377\330\377\340\\0\020JFIF\\0\001\001\\0\\0\001\\0\001\\0\\0\377\341\\0\234Exif\\0\\0II*\\0\010\\0\\0\\0\007\\0\\0\001\003\\0\001\\0\\0\\0S\002\\0\\0\001\001\003\\0\001\\0\\0\\0\026\002\\0\\0\022\001\003\\0\001\\0\\0\\0\\0\\0\\0\\02\001\002\\0\024\\0\\0\\ (...)"
And the form that i retrieve the values in my table
<?php
$query = "SELECT * FROM img ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
echo($row['nombre']);
$dat= pg_unescape_bytea($row['nombre']);
echo "<img src='".$dat."'";
}
?>
However when i try to retrieve the information i just get Resource id #2 and a Warning: pg_unescape_bytea() expects parameter 1 to be string
This is the testView
<script>
$(document).ready(function(){
$('#insert').click(function(){
var image_name = $('#image').val();
if(image_name == '')
{
alert("Please Select Image");
return false;
}
else
{
var extension = $('#image').val().split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert('Invalid Image File');
$('#image').val('');
return false;
}
}
});
});
</script>
<?php
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
if(isset($_POST["insert"]))
{
$file = pg_escape_bytea(addslashes(file_get_contents($_FILES["image"]["tmp_name"])));
$sql = 'INSERT INTO img (nombre) VALUES (?)';
$ISp_Res = $db->prepare($sql);
$ISp_Res->bindParam(1, $file);
$ISp_Res->execute();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Insert and Display Images From Mysql Database in PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<h3 align="center">Insert and Display Images From Mysql Database in PHP</h3>
<br />
<form method="post" enctype="multipart/form-data">
<input type="file" name="image" id="image" />
<br />
<input type="submit" name="insert" id="insert" value="Insert" class="btn btn-info" />
</form>
<br />
<br />
<table class="table table-bordered">
<tr>
<th>Image</th>
</tr>
<?php
$query = "SELECT * FROM img ORDER BY id DESC";
$db = new PDO("pgsql:host=localhost;port=5432;dbname=sac;user=postgres;password=insertPass");
$result = $db->prepare($query);
$results = $result->execute();
$results = $result->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
echo($row['nombre']);
$dat= pg_unescape_bytea($row['nombre']);
echo "<img src='".$dat."'";
}
?>
</table>
</div>
</body>
</html>
Please tell me where im doing it wrong :(
Don't use addslashes() while inserting.
$target_file = '/path/to/file.jpg';
$img = fopen($target_file, 'r');
$data = fread($img, filesize($target_file));
$file = pg_escape_bytea($data);
While fetching data use
ob_start();
fpassthru($row['nombre']);
$dat= ob_get_contents();
ob_end_clean();
$dat= "data:image/*;base64," . base64_encode($dat);
echo "<img src='".$dat."'";
I have code for image upload and view in php and MySQL. After click on "Submit" button in "imageUpload.php" page image is stored in database. but not displaying in "listImages.php" page. I don't know what's the problem. I see "image not displaying when uploading in php" but its seems different solution for me. here is my code please have a look where i am wrong.
imageUpload.php :
<?php
/* CREATE TABLE IF NOT EXISTS `output_images`
(
`imageId` tinyint(3) NOT NULL AUTO_INCREMENT,
`imageType` varchar(25) NOT NULL DEFAULT '',
`imageData` mediumblob NOT NULL,
PRIMARY KEY (`imageId`)
) */
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysqli_connect("localhost", "root", "");
mysqli_select_db ("test");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO output_images(imageType ,imageData)
VALUES('{$imageProperties['mime']}', '{$imgData}')";
$current_id = mysqli_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image to MySQL BLOB</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</BODY>
</HTML>
listImages.php :
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db("test");
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
$result = mysqli_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysqli_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" /><br/>
<?php
}
mysqli_close($conn);
?>
</BODY>
</HTML>
imageView.php :
<?php
$conn = mysqli_connect("localhost", "root", "");
mysqli_select_db("test") or die(mysqli_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysqli_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysqli_error());
$row = mysqli_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
mysqli_close($conn);
?>
this would help you
<a href="imageView.php?image_id=<?php echo $row["imageId"]; ?>">
<img src="<?php echo $row['imagedata']; ?>" alt="my picture" height="128" width="128" />
</a>
it should be
$conn=mysqli_connect("ur_servername_ex_localhost","ur_username","ur_password","ur_db");
mysqli_query($conn, $sql);
I am trying to insert and retrieve image from database. All is going well and image is being inserted in database in BLOB format, but when I am trying to retrieve those images it does not appear and only broken icon comes to webpage. The code is given below. Please help.
ImageUpload.php
<?php
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysql_connect("localhost", "root", "");
mysql_select_db ("connection");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO output_images(imageType ,imageData)
VALUES('{$imageProperties['mime']}', '{$imgData}')";
$current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysql_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image to MySQL BLOB</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</BODY>
</HTML>
ListImages.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("connection");
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
$result = mysql_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysql_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" /><br/>
<?php
}
mysql_close($conn);
?>
</BODY>
</HTML>
imageView.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("connection") or die(mysql_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
mysql_close($conn);
?>
I'm having a problem on developing my website..
First, I have 2 tables:
1- Products: contains info. about the products & 2- Images: which contains product images.
The idea is that : I want to insert an image or two for a specified product and display that image for that product only..
In the mean time, I can insert images into the database and I can also display them.. but my issue is that when I try to do display.. the code retrieves all images from Images table..
so my question: how can I display image/s for only one product .. not all images in that table? I'm confused in how to make this condition.. need ur help guys :?
Here's my code:
File1: imageUpload.php
<?php
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysql_connect("localhost", "root", "");
mysql_select_db ("myDB");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO Images(imageType ,imageData, product_id)
VALUES('{$imageProperties['mime']}', '{$imgData}','{$_POST['memids']}')";
$current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" .
mysql_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post"
class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" required/>
<input type="submit" name="submit" value="Submit" class="btnSubmit" /><br><br>
</form>
</div>
</BODY>
</HTML>
File2: listImages.php
<?ob_start()?>
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("myDB");
$sql = "SELECT imageId FROM Images
ORDER BY imageId DESC";
$result = mysql_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysql_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?> "width="200" /><br/>
<?php
}
mysql_close($conn);
?>
</BODY>
</HTML>
<?ob_flush()?>
File3: imageView.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("myDB") or die(mysql_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM Images WHERE imageId=" . $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
mysql_close($conn);
?>