in mysql Datbase there is images stored using php Script (image got from a form.html/POST method) let's cal them (phpImages). and there is others stored using android application ( by converting Bitmap to String and using StringBuilder ). let's call them (androidImages).
with this php script i can load and display phpImages, but i cannot display androidImages.
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "SELECT image FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
echo ( $result['image']);
mysqli_close($con);
}
?>
with this php script i can load androidImages, but i cannot load phpImages :
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "SELECT image FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
echo base64_decode( $result['image'] );
mysqli_close($con);
}
?>
i wan't a php script that could display the both. because i want to load all images in a ListView of an android Apps.
**This is php script relied to android Application : **
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$image = $_POST['image'];
$con=mysqli_connect("localhost","root","","othmane")or die(mysqli_error($con));
$sql = "INSERT INTO images (image,image_type) VALUES (?,'android')";
$stmt = mysqli_prepare($con,$sql);
mysqli_stmt_bind_param($stmt,"s",$image);
mysqli_stmt_execute($stmt);
$check = mysqli_stmt_affected_rows($stmt);
if($check == 1){
echo "Image Uploaded Successfully";
}else{
echo "Error Uploading Image";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
this is php Script relied with Form.html post method :
<?php
echo ini_get( 'file_uploads' );
if(!isset($_POST['submit'])){
echo '<p>Please Select Image to Upload</p>';
}
else
{
try {
upload();
}
catch(Exception $e)
{
echo '<h4>'.$e->getMessage().'</h4>';
}
}
function upload(){
$imgfp = fopen($_FILES['photo']['tmp_name'], 'rb');
print_r($_FILES);
$dbh = new PDO("mysql:host=localhost;dbname=othmane", 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh->prepare("INSERT INTO images (image,image_type) VALUES (?,'php')");
$stmt->bindParam(1, $imgfp, PDO::PARAM_LOB);
$stmt->execute();
}
?>
Add a column called image_type in your table and pass one of the following values to determine what the source of the image is upon uploading: phpImage or androidImage
So you can do:
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
$id = $_GET['id'];
$sql = "SELECT image, image_type FROM images WHERE id = '$id'";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));
$result = mysqli_fetch_array($r);
header('Content-Type: image/jpeg');
if ($result['image_type'] == 'phpImage') {
echo ( $result['image']);
} else if ($result['image_type'] == 'androidImage') {
echo base64_decode( $result['image'] );
}
mysqli_close($con);
}
?>
Related
I successfully can upload the image into MySQL but when trying to display the image from the MySQL they appear broken.
$image = $_FILES['image']['tmp_name'];
$sql = "INSERT INTO images (image,id) VALUES(?,?)";
$statement = $conn->prepare($sql);
$statement->bind_param('si', $image, $id);
$statement->execute();
$check = mysqli_stmt_affected_rows($statement);
if($check == 1){
$msg = 'Image was uploaded';
}else{
$msg = 'Something went wrong!';
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<button>Upload</button>
</form>
<?php
echo $msg;
?>
<?php
$sql = "SELECT image_id, image, id FROM images WHERE id = ?";
$statement = $conn->prepare($sql);
$statement->bind_param('i', $id);
$statement->execute();
$result = $statement->get_result();
foreach($result as $row){
echo '<img src="data:image/jpg;base64,'.base64_encode($row['image'] ).'" height="200" width="200"/>';
}
Not sure what I did wrong any help would be much appreciated. Just playing around with this type of thing not a production product or I'd have put the form away from the code.
EDIT!
database screenshot
So I edited my code as suggested...now the image isn't being saved as a blob at all the blob section is empty which is a issue.
$msg = '';
$id = $_SESSION['id'];
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$image = fread($fp, filesize($tmpName));
fclose($fp);
$sql = "INSERT INTO images (image,id) VALUES(?,?)";
$statement = $conn->prepare($sql);
$statement->bind_param('bi', $image, $id);
$statement->execute();
$check = mysqli_stmt_affected_rows($statement);
if($check == 1){
$msg = 'Image was uploaded';
}else{
$msg = 'Something went wrong!';
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<button>Upload</button>
</form>
<?php
echo $msg;
?>
<?php
$sql = "SELECT image_id, image, id FROM images WHERE id = ?";
$statement = $conn->prepare($sql);
$statement->bind_param('i', $id);
$statement->execute();
$result = $statement->get_result();
foreach($result as $row){
echo '<img src="data:image/jpg;base64,'.base64_encode($row['image'] ).'" height="200" width="200"/>';
}
?>
Please use fread (or file_get_contents) to get the binary data uploaded and
Please specify "b" (blob) for binary data when using bind_param
For uploading graphic (which for sure is not too small in size), use send_long_data().
Reason:
If data size of a variable exceeds max. allowed packet size (max_allowed_packet), you have to specify b in types and use mysqli_stmt_send_long_data() to send the data in packets.
The above is quoted from the following official documentation:
https://www.php.net/manual/zh/mysqli-stmt.bind-param.php
Hence change
$image = $_FILES['image']['tmp_name'];
$sql = "INSERT INTO images (image,id) VALUES(?,?)";
$statement = $conn->prepare($sql);
$statement->bind_param('si', $image, $id);
$statement->execute();
to
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$image = fread($fp, filesize($tmpName));
fclose($fp);
// alternative method
//$image = file_get_contents($tmpName);
$sql = "INSERT INTO images (image,id) VALUES(?,?)";
$statement = $conn->prepare($sql);
$null = NULL;
$statement->bind_param('bi', $null, $id);
$statement->send_long_data(0, $image);
$statement->execute();
Note:
The $null variable is needed, because bind_param() always wants a variable reference for a given parameters. In this case the "b" (as in blob) parameter. So $null is just a dummy, to make the syntax work.
In the next step we need to "fill" the blob parameter with the actual data. This is done by send_long_data(). The first parameter of this method indicates which parameter to associate the data with. Parameters are numbered beginning with 0. The second parameter of send_long_data() contains the actual data to be stored.
So, for your case, you may use the following sample code (tested - 100% working):
<?php
session_start();
$servername = "localhost";
$username = "xxxxxx";
$password = "xxxxxxxxxxxx";
$dbname = "xxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
$msg = '';
$id = $_SESSION['id'];
$id=1234; // I set this value for testing
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$image = fread($fp, filesize($tmpName));
fclose($fp);
$sql = "INSERT INTO images (image,id) VALUES(?,?)";
$statement = $conn->prepare($sql);
$null = NULL;
$statement->bind_param('bi', $null, $id);
$statement->send_long_data(0, $image);
$statement->execute();
$check = mysqli_stmt_affected_rows($statement);
if($check == 1){
$msg = 'Image was uploaded';
}else{
$msg = 'Something went wrong!';
}
}
?>
<form action="#" method="post" enctype="multipart/form-data">
<input type="file" name="image" />
<button>Upload</button>
</form>
<?php
echo $msg;
?>
<?php
$sql = "SELECT image_id, image, id FROM images WHERE id = ?";
$statement = $conn->prepare($sql);
$statement->bind_param('i', $id);
$statement->execute();
$result = $statement->get_result();
foreach($result as $row){
echo '<img src="data:image/jpg;base64,'.base64_encode($row['image']).'" height="200" width="200"/>';
echo "<br>";
}
?>
I want edit record in db table but it doesn't save in db table and nothing changed after i submit this form.
Here codes that i forgot to put.
<?php
require('db.php');
include("auth.php"); //include auth.php file on all secure pages
$id_doc=$_REQUEST['id_doc'];
$query = "SELECT * from doc where id_doc='".$id_doc."'";
$result = mysqli_query($connection, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
?>
This is my php codes
<?php
if(isset($_POST['new']) && $_POST['new']==1)
{
$id_doc=$_REQUEST['id_doc'];
$query = "SELECT * from doc where id_doc='".$id_doc."'";
$result = mysqli_query($connection, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
$title =$_REQUEST['title'];
$date = $_REQUEST['date'];
$from_to = $_REQUEST['from_to'];
$details = $_REQUEST['details'];
$d_location = $_REQUEST['d_location'];
$d_stat = $_REQUEST['d_stat'];
$update="update doc set title='".$title."', date='".$date."', from_to='".$from_to."', details='".$details."', d_location='".$d_location."', d_stat='".$d_stat."' where id_doc='".$id_doc."'";
mysqli_query($connection, $update) or die(mysql_error());
$status = "File Record Updated Successfully. </br></br><a href='v_doc.php'>View Updated Record</a>";
echo '<p style="color:#FF0000;">'.$status.'</p>';
}else {
// here some else code
}
?>
Not an answer. Too long for a comment.
The issue of parametrised queries aside, I find this easier to read:
UPDATE doc
SET title = '$title'
, date = '$date'
, from_to = '$from_to'
, details = '$details'
, d_location = '$d_location'
, d_stat = '$d_stat'
WHERE id_doc = '$id_doc'
And now see about parametrised queries
Try below:
<?php
if(isset($_POST['new']) && $_POST['new']==1)
{
$id_doc=$_REQUEST['id_doc'];
$query = "SELECT * from doc where id_doc='".$id_doc."'";
$result = mysqli_query($connection, $query) or die ( mysqli_error());
$row = mysqli_fetch_assoc($result);
$title =$_REQUEST['title'];
$date = $_REQUEST['date'];
$from_to = $_REQUEST['from_to'];
$details = $_REQUEST['details'];
$d_location = $_REQUEST['d_location'];
$d_stat = $_REQUEST['d_stat'];
$update="update doc set title='".$title."', date='".$date."', from_to='".$from_to."', details='".$details."', d_location='".$d_location."', d_stat='".$d_stat."' where id_doc='".$id_doc."'";
if(mysqli_query($connection, $update)) {
$status = "File Record Updated Successfully. </br></br><a href='v_doc.php'>View Updated Record</a>";
} else {
die(mysqli_error($connection));
}
echo '<p style="color:#FF0000;">'.$status.'</p>';
} else {
// here some else code
}
?>
This should show you exact error, once you get it. show it here, so we can check and do correction.
Now my PHP can display Blob from MySQL on web browser with http://localhost/download.php?id=1
How to display this with webview on android?
<?php
if($_SERVER['REQUEST_METHOD']=='GET'){
$id = $_GET['id'];
$sql = "select * from loancontract where id = '$id'";
require_once('db_connect.php');
$r = mysqli_query($con,$sql);
$result = mysqli_fetch_array($r);
header('content-type: application/pdf');
echo base64_decode($result['data']);
mysqli_close($con);
} else {
echo "Error";
}
?>
I'm trying to display on the browser 3 images stored in mysql database , but i figured out that just the first image of the first iteration on loop WHILE is displayed. how to display the 3 images in the browser ?
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
//$id = $_GET['id'];
$sql = "SELECT image,image_type FROM images where id between 2 and 6";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
$result=mysqli_fetch_array($r);
header('Content-Type:image/jpeg');
$ss=$result['image_type'];
while($row = $r->fetch_assoc()){
if ($ss == 'php') {
echo ( $result['image']);
} else if ($ss == 'android') {
echo base64_decode( $result['image'] );
}
}
}else{
mysqli_close($con);
}
?>
this code :
<?php
$con = mysqli_connect("localhost","root","","othmane") or die(mysqli_error($con));
if($_SERVER['REQUEST_METHOD']=='GET'){
//$id = $_GET['id'];
$sql = "SELECT image,image_type FROM images where id between 1 and 3";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));;
//$result=mysqli_fetch_array($r);
$result=var_dump(mysqli_fetch_all($r));
//header('Content-Type:image/jpeg');
while($row = mysqli_fetch_assoc($r))
{
var_dump($row) ;
}
/*while($row = $r->fetch_assoc()){
$ss=$row['image_type'];
if ($ss == 'php') {
echo ( $row['image']);
} else if ($ss == 'android') {
echo base64_decode( $row['image'] );
}
}*/
}
else{
mysqli_close($con);
}
?>
and this is the result :
edit. as i've looked throught the problem, you should be able to do:
<img src="data:image/jpeg;base64,
<?php echo base64_encode( $image_data ); ?>
" />
to display all of your image, so below should work:
while($row = mysqli_fetch_assoc($r)){
$ss = $row['image_type'];
if ($ss == 'php') {
<img src="data:image/jpeg;base64, <?php echo ( $row['image']); ?>" />
} else if ($ss == 'android') {
<img src="data:image/jpeg;base64, <?php echo base64_decode( $row['image'] ); ?> " />
}
}
When you are doing $r->fetch_assoc() ( so as long as your query is getting you result, your While loop will go on), you are fetching one result row of your data into associative array, so you have your data in $row variable.
You have to use that variable for checking your ['image_type'] and getting your ['image'].
In your code your $result['image_type'] and $result['image'] was bound to the first record that you have fetched with $result=mysqli_fetch_array($r) ( as documentation states: mysqli_result::fetch_array -- mysqli_fetch_array — Fetch a result row as an associative, a numeric array, or both ).
if($_SERVER['REQUEST_METHOD']=='GET'){
$sql = "SELECT image,image_type FROM images where id BETWEEN 2 and 6";
$r = mysqli_query($con,$sql) or die(mysqli_error($con));
header("Content-type: image/jpeg");
while($row = mysqli_fetch_assoc($r)){
$ss = $row['image_type'];
if ($ss == 'php') {
echo ( $row['image']);
} else if ($ss == 'android') {
echo base64_decode( $row['image'] );
}
}
}else{
mysqli_close($con);
}
also when you are using procedular style, use it all the way, as (examples from php.net):
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_assoc($result)) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
or just use object oriented style:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
$query = "SELECT Name, CountryCode FROM City ORDER by ID DESC LIMIT 50,5";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
printf ("%s (%s)\n", $row["Name"], $row["CountryCode"]);
}
More info, examples here: mysqli_result::fetch_assoc
I have an old mysql code where it successfully inserts the name of an image file into the database. But since old mysql is being decapitated, I have attempted doing the same in mysqli (can't use PDO because of version of PHP I have). The problem is that I cannot get the image file name to be inserted into the database in mysqli. What am I doing wrong?
Below is the mysqli code:
<?php
session_start();
$username="xxx";
$password="xxx";
$database="mobile_app";
$mysqli = new mysqli("localhost", $username, $password, $database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
die();
}
$result = 0;
if(getimagesize($_FILES['fileImage']['tmp_name'])){
if( is_file("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( is_file("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
$insert->bind_param("s",'ImageFiles/' . $_FILES['fileImage']['name']);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES (?)";
if (!$insert = $mysqli->prepare($imagesql)) {
// Handle errors with prepare operation here
}
$insert->bind_param("s",'ImageFiles/' . $_FILES['fileImage']['name']);
$insert->execute();
if ($insert->errno) {
// Handle query error here
}
$insert->close();
}
}
?>
Below is the old mysql code where the insert did work:
<?php
session_start();
$username="xxx";
$password="xxx";
$database="mobile_app";
mysql_connect('localhost',$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$result = 0;
if(getimagesize($_FILES['fileImage']['tmp_name'])){
if( is_file("ImageFiles/".$_FILES['fileImage']['name'])) {
$parts = explode(".",$_FILES['fileImage']['name']);
$ext = array_pop($parts);
$base = implode(".",$parts);
$n = 2;
while( is_file("ImageFiles/".$base."_".$n.".".$ext)) $n++;
$_FILES['fileImage']['name'] = $base."_".$n.".".$ext;
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
else
{
move_uploaded_file($_FILES["fileImage"]["tmp_name"],
"ImageFiles/" . $_FILES["fileImage"]["name"]);
$result = 1;
$imagesql = "INSERT INTO Image (ImageFile)
VALUES ('ImageFiles/".mysql_real_escape_string($_FILES['fileImage']['name'])."')";
mysql_query($imagesql);
}
}
mysql_close();
?>
<script language="javascript" type="text/javascript">
window.top.stopImageUpload(<?php echo $result ? 'true' : 'false'; ?>, '<?php echo $_FILES['fileImage']['name'] ?>');
</script>
Try this, assign the value to a variable first and then bind it, dont build the data within the bind_param:
<?php
$imagesql = "INSERT
INTO Image (ImageFile)
VALUES (?)";
$insert = $mysqli->prepare($imagesql);
//Dont pass data directly to bind_param store it in a variable
$insert->bind_param("s",$img);
//Assign the variable
$img = 'ImageFiles/'.$_FILES['fileImage']['name'];
$insert->execute();
?>
Also you should check if the file is uploaded and if any errors have occurred with the upload before doing any db stuff:
<?php
//If POST
if($_SERVER['REQUEST_METHOD']=='POST'){
//Check no errors on upload
if($_FILES['fileImage']['error']==0){
if(isset($_FILES['fileImage']['tmp_name'])){
$imgSize = getimagesize($_FILES['fileImage']['tmp_name']);
...
...
}
}else{
//get error code and display error
}
}else{
//No POST
}
?>