Problem Statement : I'm uploading images in MYSQL database using POST request with Swift & PHP. I'm able to insert selected image in database. But unable to display it.
MYSQL Table Format :
And now I'm displaying this images from database to my localhost. Which gives me result as follows...
Swift File :
@IBAction func uploadOnServer(sender: AnyObject)
{
if Description.text == "" || imageView.image == nil
{
}
else
{
let img:UIImage = imageView.image!
let request = NSMutableURLRequest(URL:NSURL(string: "http://localhost/RESTAPI/UploadImage.php")!)
request.HTTPMethod = "POST"
let postString = "img=\(img)"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request)
{
data, response, error in
print("response =\(response)")
if error != nil
{
print("error=\(error)")
return
}
}
task.resume()
Description.text = ""
imageView.image = nil
}
}
PHP File :
<?php
$host = "localhost";
$username = "scott";
$password = "tiger";
$dbname = "mydb";
$link = mysqli_connect($host, $username, $password, $dbname);
$arr = array();
if($link == true)
{
//Displaying images from mysql
$select_image="select * from images";// where id=1";
$var=mysqli_query($link,$select_image);
echo "<table>";
while($row=mysqli_fetch_array($var))
{
//$desc = $row["Description"];
$img = $row['image'];
echo "<tr>";//<td><b>$desc</b></td>";
echo "<td><img src = '$img' width = 100 height = 100></td></tr>";
}
}
else
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$img = $_REQUEST['img'];
$sql1 = "INSERT INTO images (image) VALUES ('$img')";
if(mysqli_query($link, $sql1))
{
echo "Image added successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql1.mysqli_error($link)";
}
}
mysqli_close($link);
?>
Getting the image from the user
See http://php.net/manual/en/reserved.variables.files.php and http://php.net/manual/en/features.file-upload.php and friends for the datails of how to use $_FILES
to receive the uploaded.
Once you have the image in a variable, say $jpg
, do not use any text encode/decode functions; it will only mangle things. The different approaches below will say what to do to avoid tripping over 8-bit codes.
There are three ways to present the image, each is somewhat complex
Storing the image in the database; showing image inline
I have used this approach for thumbnails, but don't recommend for big images.
Store it in a MEDIUMBLOB
in a table, use bin2hex()
in PHP to turn the image into a string. Then use INSERT ... VALUES (UNHEX('...'))
to switch back to binary at the MySQL server side.
After reloading, have the referencing PHP say something like
$b64 = base64_encode($blob);
echo "<img src='data:image/jpeg;base64,$b64'/>";
Storing the image in the database; PHP script to generate image
I use this when I want to use PHP's "image*" functions to modify the image before displaying it. Since this is more involved than you probably need, I will only skim over what needs doing.
The html for the page would invoke another script, with whatever arguments you need:
<img src=modify.php?this=stuff&that=stuff>
Then in modify.php
, start with
header('Content-type: image/jpeg');
And end with this (assuming you are building a JPEG):
imagejpeg($im);
Storing the image in a file
This is the preferred way that most of the big web sites do it most of the time.
If your file comes from an upload, then something like this moves it to a better path without having to touch the jpg.
$tmpfile = $_FILES['userfile']['tmp_name'];
move_uploaded_file($tmpfile, $uploadfile);
More info and examples: http://php.net/manual/en/function.move-uploaded-file.php
In the HTML, simply generate something like this:
<img src=path/to/file>
Do some research on where in your server's path you can put images, and make sure the permissions are adequate.
Note: The database is not involved in holding the image, instead it has a column for holding the url "path/to/file"
:
image VARCHAR(255) NOT NULL
For further discussion
- Which of the 3 techniques would you like to dig deeper into?
- Let's see the HTML you are generating.
- Let's see
SHOW CREATE TABLE
.
Create another PHP file that outputs the raw image file with echo. This php file will accept a $_GET parameter that identifies the image... the image id will do. Then echo the image... the image could be retrieved like this:
<img src="imagephpfile.php?id=10" />
where id is the id in the db.... imagephpfile.php is the php file you made.
This solution is similar to this one:
Can't display BLOB stored in database
OR:
use base64 encode the content like this:
PHP display image BLOB from MySQL
Let me know if this helps you might need to tweak it slightly but should do what you wanted:
<?php
$host = "localhost";
$username = "scott";
$password = "tiger";
$dbname = "mydb";
$link = mysqli_connect($host, $username, $password, $dbname);
$arr = array();
if($link == true)
{
//Displaying images from mysql
$select_image = "SELECT * FROM images //WHERE id = $id";
$sth = $link->query($select_image);
$result=mysqli_fetch_array($sth);
//$var=mysqli_query($link,$select_image);
echo "<table>";
//$desc = $row["Description"];
echo "<tr>";//<td><b>$desc</b></td>";
echo '<td><img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/></td></tr>';
echo "</table>";
}
else
{
die("ERROR: Could not connect. " . mysqli_connect_error());
}
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$img = $_REQUEST['img'];
$sql1 = "INSERT INTO images (image) VALUES ('$img')";
if(mysqli_query($link, $sql1))
{
echo "Image added successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql1.mysqli_error($link)";
}
}
mysqli_close($link);
?>