How to display an image from a mysql database? - php

This is the structure of my mysql table crij_personne :
id
photo longblob
image_name varchar(64)
My html code is the following:
<input type="file" name="photo" />
The code for uploading the image to my database:
$imagetmp=addslashes (file_get_contents($_FILES['photo'] ['tmp_name']));
$image_name = addslashes($_FILES['photo']['image_name']);
$imagetmp= base64_encode($imagetmp);
$sql = "INSERT INTO crij_personne (description, photo, image_name) VALUES ('".$_POST['description']."','$imagetmp',' $image_name');";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
The code for displaying the image on a web page is:
echo '<img height="300" width="300" src="data:image;base64, '.$row['photo'].'">';
But nothing is happening... I'm doing something wrong, obviously.
Thanks for the help.

Try this one.
For insertion values into the database.
$image_name = addslashes($_FILES['photo']['image_name']);
$sql = "INSERT INTO crij_personne (description, photo, image_name) VALUES ('".$_POST['description']."','$imagetmp',' $image_name');";
if (mysqli_query($conn, $sql)) echo "New record created successfully";
else echo "Error: " . mysqli_error($conn);
For retrieval of image from Database
$connectDb = mysqli_connect("localhost","root","password","DatabaesName"); //You need to replace with your own credentials
$query= "SELECT * FROM crij_personne WHERE id = $id";
$sth = $connectDb ->query($query);
$mysqli_fetch_array=mysqli_fetch_array($sth);
header("Content-type: image/jpeg");
echo '<img src="data:image/jpeg;base64,'.base64_encode( $mysqli_fetch_array['image_name'] ).'"/>';
And then retrieve, I hope you will get the correct output.

Related

store data to 2 tables with foreign key in MySql php

I have two table in MySql, which are table 1 and table 2. As I want to link table 1 to 2 via userID. However, the funciton I have come out is not working.
MySQl tables are below:
In my case, userId will be the foreign key to link these 2 tables.
However, my functions are not working.
This is my function below:
function insert() {
function adduserdetails($con, $accountId, $name, $contact) {
$query = "insert into userdetails(accountId,name,contact)
values('$accountId','$name','$contact')";
//echo "{$sqlString}";
$insertResult = mysqli_query($con, $query);
if ($insertResult) {
echo " Applicant Detail Added !<br />";
echo "<a href='index.php'>Back to Home</a>";
} else {
echo " Error !";
echo "{$query}";
//header('Location: post.php');
}
}
}
if ($con->query($query) === TRUE) {
$last_id = $con->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $query . "<br>" . $con->error;
}
function adduseremployment($con,$last_id,$occupationMain,$comapny){
$query1 = "insert into useremployment(userId,Occupation,company)
values('$last_id',$occupationMain','$comapny')";
//echo "{$sqlString}";
$insertResult = mysqli_query($con, $query1);
if($insertResult){
echo " Applicant Detail Added !<br />";
echo "<a href='index.php'>Back to Home</a>";
}
else {
echo " Error !";
echo "{$query1}";
//header('Location: post.php');
}
}
You have vertical table.
Check below code,
Be remember to prepare statement.
<?php
function addUser(){
// parent table.
$queryParent = ''; // Your userdetails table insert query
$insertResult = mysqli_query($con, $queryParent);
$userId = mysqli_insert_id($con); // This is your last inserted userId.
// child table.
$queryChild = ''; // Your useremployment table insert query with userId.
$insertResult = mysqli_query($con, $queryChild);
}
?>
your Query is wrong, please check this,
$query1 = "insert into useremployment(userId,occupation,company)
values('$last_id',$occupationMain','$comapny')";
you have to store record on userId as a refrence not to "accountID".
hope it helps,
In second insert you are using wrong column name (userID and not accountID)
$query1 = "insert into useremployment(userID,Occupation,company)
^^^^^^ here
values('$last_id',$occupationMain','$comapny')";
and in function signature and body you have comapny (could be you want company)

How can I correctly display an image from my database/table using a php form?

Here are the following scripts I have created. first is the form that allows to select an image to be displayed. Second is the display page. My question is how can I display images from my form using a database/table in php?? I only want to display a single image that I have selected using the select file form.
<!DOCTYPE html>
<html>
<body>
<form action="display.php" method="post" enctype="multipart/form-data">
Select image to display:
<input type="file" name="fileToDisplay" id="fileToDisplay">
<input type="submit" value="Display Image" name="submit">
</form>
</body>
</html>
This is the second script
<?php
$db = mysqli_connect("localhost","root", "", "myDB");
$sql = "SELECT * FROM images";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<img src=' images/". $row['image']."' >";
echo "<p>". $row['text']."</p>";
echo "</div>";
}
The simplest way of doing this is to upload the image to the server and save the image name in your database.
Uploading the image to the server and saving to the database
// display.php
$tmp_file = $_FILES['fileToDisplay']['tmp_name']; // get the temp name of the image
$name = $_FILES['fileToDisplay']['name']; // get the name of the image
Now you need to move the file to a directory on your server with move_uploaded_file() and save the name of the file in the database.
move_uploaded_file($tmp_file, 'images/' . $name)
$remove_extension = explode('.', $name);
$sql = "INSERT INTO `images`(`image`, `text`) VALUES ('$name', '$remove_extension[0]')";
Complete code
// display.php
$tmp_file = $_FILES['fileToDisplay']['tmp_name'];
$name = $_FILES['fileToDisplay']['name'];
if (move_uploaded_file($tmp_file, 'images/' . $name)) {
$remove_extension = explode('.', $name);
$sql = "INSERT INTO `images`(`image`, `text`) VALUES ('$name', '$remove_extension[0]')";
if (mysqli_query($db, $sql)) {
$last_id = $db->insert_id;
$sql = "SELECT * FROM images WHERE id = $last_id";
$result = mysqli_query($db, $sql);
while ($row = mysqli_fetch_array($result)){
echo "<div><img src=' images/". $row['image']."' >";
echo "<p>". $row['text']."</p>";
echo "</div>";
}
}
}
Handling file uploads

php image type blob wont show

I am trying to show the blop images i have in my mysql database. But all i get is a whitebox with no picture in it.
PHP code:
<?php
require_once "include/config.php";
session_start();
$sql = "SELECT * FROM docenten";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo "<dt><strong>Foto:</strong></dt><dd>" .
'<img src="data:image/jpeg;base64,'.
base64_encode($row['foto']).
'" width="290" height="290">' . "</dd>";
}
}else{
echo "0 result";
}
?>
But when the code runs all i get is this: http://imgur.com/nhIO2LQ
Anyone know a solution?
use addslashes before insert
$img = addslashes(file_get_contents($_FILES['images']['tmp_name']));
$query = "INSERT INTO tableName (id,image) VALUES('','$image')";

Display image from MySql database in Php server

I send an image from my Android Application to my Php server using a MySql database, but when i try to display the image in browser it doesn't work.
This is how I send the picture
String imageString=Base64.encodeBytes(this.image);
nameValuePairs.add(new BasicNameValuePair("image", imageString));
And this is how I try to display it
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
I've checked and imageString in my app is different from base64_encode( $row['image']).
MySql part
$conn = new mysqli($server, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// sql to create table
$sql = "CREATE TABLE Posts (
id INTEGER UNSIGNED AUTO_INCREMENT PRIMARY KEY,
user VARCHAR(50) NOT NULL,
date VARCHAR(12) NOT NULL,
event VARCHAR(1000),
image BLOB
)";
if ($conn->query($sql) === TRUE) {
echo "Table Posts created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
$conn->close();
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$user = $_POST['user'];
$date = $_POST['date'];
$event = $_POST['event'];
$image = $_POST['image'];
echo "Test";
$sql = "INSERT INTO Posts (user, date, event,image) ";
$sql .= "VALUES ('$user','$date', '$event', '$image')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Insert success";
}
mysql_close($con);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["user"]. $row["date"]. $row["event"]. "<br>";
echo '<img src="data:image/jpeg;base64,'.base64_encode( $row['image'] ).'"/>';
Your Java code is doing a Base64 encode of the image before sending it to the server. You do not need to encode it a second time when you go to display it. The result is a base64 encoded string of a base64 encoded string, which isn't what you want to do.
Try this instead:
echo '<img src="data:image/jpeg;base64,' . $row['image'] . '"/>';

broken file icon retrieving image from database php and mysql

I need to upload and retrieve image from a database, I am able to store the image in the database but unable to display it later. please help
I wrote the following code to retrieve from the database.
$result1=mysql_query("INSERT INTO userdata(id, username, firstname, lastname, imageType, image)VALUES('', '" . $_SESSION['username'] . "', '" . $_SESSION['firstname'] . "', '$lastname','{$image_size['mime']}','{$imgData}')") or die("Invalid query: " . mysql_error());
if($result1)
{
echo "</br>";
echo "Registration successful";
echo "</br>";
echo $lastid=mysql_insert_id();//get the id of the last record
echo "uploaded image is :"; ?>
<img src="imageView.php?image_id=<?php echo $lastid; ?>" /><br/>
<?php
echo "</br>";
}#if result1into db successful
else
{
echo $result1;
echo "Problem in database operation";
imageView.php has the following code:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("wordgraphic") or die(mysql_error());
if(isset($_GET['id'])) {
$sql = "SELECT imageType,image FROM userdata WHERE id=". $_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["image"];
}
mysql_close($conn);
?>
What could be possibly wrong with the code?
When i try to run imageView.php with static id image is getting displayed. So i guess the error is in passing the variable is this code:
echo "uploaded image is :"; ?>
<img src="imageView.php?image_id=<?php echo $lastid; ?>" /><br/>
<?php
what could be possibly wrong?
just a smal rectification
<img src="imageView.php?image_id=<?php echo $lastid; ?>" />
instead of this
src = src path where u r saving the image file lets say in images folder that would be here $imagedata store the file name in the DB so that you can retreive it from the image folder
<img src="images/$imgData" width="your wish" height="your wish"/>

Categories