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>";
}
?>
Related
Im trying to show images that i uploaded to the database using longblob and PDO but i always get a black screen with a small white square in the center.
This is the code:
<?php
include('snippets/startDB.php');
include('snippets/Session.php');
$PicNum = $_GET["PicNum"]; echo($PicNum);
$id = $_SESSION['id'];
$stmt = $dbh->prepare('SELECT imagem FROM aluno WHERE id= ?');
$stmt->execute(array($PicNum));
$row = $stmt->fetch();
Header( 'Content-type: image/gif');
echo $row['imagem'];
?>
I think the save file is working correctly because a file appears in the database when i upload the image.
My save file:
<?php
$imagem = $_FILES["imagem"];
include('snippets/startDB.php');
include('snippets/Session.php');
if($imagem != NULL) {
$nomeFinal = time().'.jpg';
if (move_uploaded_file($imagem['tmp_name'], $nomeFinal)) {
$tamanhoImg = filesize($nomeFinal);
$mysqlImg = addslashes(fread(fopen($nomeFinal, "r"), $tamanhoImg));
if($_SESSION['tipo']== 'Aluno'){
$stmt = $dbh->prepare('UPDATE aluno SET imagem = ? WHERE id = ?');
$stmt->execute(array($mysqlImg, $_SESSION["id"]));
}else if($_SESSION['tipo']== 'Professor'){
$stmt = $dbh->prepare('UPDATE professor SET imagem = ? WHERE id = ?') ;
$stmt->execute(array($mysqlImg, $_SESSION["id"])) ;
}
header("location:perfil_aluno.php");
}
}
else {
echo"Erro!";
}
?>
values are not mapping in database table columns
this is my code
<?php
if (isset($_POST["import"])) {
ini_set('max_execution_time', 120); //300 seconds = 5 minutes
//$filename = $_FILES['file']['name'];
$file = $_FILES['file']['tmp_name'];
//$ext=substr($file,strrpos($file,"."),(strlen($file)-strrpos($file,".")));
//if($ext=="csv")
$handle = fopen($file, "r");
//$c = 0;
while(($filesop = fgetcsv($handle,",")) !== false)
{
$category = mysqli_real_escape_string($filesop[0]);
$tags = mysqli_real_escape_string($filesop[1]);
$title = mysqli_real_escape_string($filesop[2]);
$url = mysqli_real_escape_string( $filesop[3]);
$description = mysqli_real_escape_string($filesop[4]);
$date = mysqli_real_escape_string($filesop[5]);
//print_r($filesop);
var_dump($filesop);
//echo $filesop[0];
$sql = "insert into report(category,tags,title,url,description,date) values ('$category','$tags','$title','$url','$description','$date')";
//$c = $c + 1;
$result=mysqli_query($conn,$sql)or die($sql."<br/><br/>".mysql_error());
//echo $sql;
//echo $filesop[1];
//echo "success";
exit();
}
//if($result){
//echo " upload success";
//ini_set('auto_detect_line_endings',FALSE);
fclose($handle);
// }
//else
// echo "cannot upload csv file";
}
mysqli_close($conn);
?>
returns null in my output screen
var_dump($filesop);
my database sample screen shot
my csv file
Marketing & Customer Analytics,Trends & Product Updates,Segment Launches Segment Select,https://martechseries.com/analytics/customer-data-platforms/segment-launches-segment-select-new-program-help-companies-leverage-first-party-data-certified-partners/,"Segment, the customer data infrastructure company, launched Segment Select, a new program designed to help Channel and Technology Partners easily build and implement solutions for their customers that leverage Segment’s Customer Data Infrastructure (CDI).",2/24/2019
The issue in your code mysqli_real_escape_string, you missed parameters in mysqli_real_escape_string function. You need to pass the database object in mysqli_real_escape_string function.
Like example :
Your code : $category = mysqli_real_escape_string($filesop[0]);
New code : $category = mysqli_real_escape_string($conn,$filesop[0]);
also helpful code below please check it.
while(($filesop = fgetcsv($handle,",")) !== false)
{
$category = mysqli_real_escape_string($conn, $filesop[0]);
$tags = mysqli_real_escape_string($conn, $filesop[1]);
$title = mysqli_real_escape_string($conn, $filesop[2]);
$url = mysqli_real_escape_string($conn, $filesop[3]);
$description = mysqli_real_escape_string($conn, $filesop[4]);
$date = mysqli_real_escape_string($conn, $filesop[5]);
$sql = "insert into report(category,tags,title,url,description,date) values ('$category','$tags','$title','$url','$description','$date')";
$result=mysqli_query($conn,$sql)or die($sql."<br/><br/>".mysqli_error($conn));
exit();
}
How can I get the base64 value properly in PHP from a submitted data?
The data being passed on is
data:image/png;base64,LongBase64ValueHereOfAnImage
Right now, I can only get it by
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list($data) = explode(',', $data);
$data = base64_decode($data);
Is there a proper way to get the base64 value?
This could be done in one line with regex
$data = $_POST['image'];
$data = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $data));
try this: uploading image code.
if (count($_FILES) > 0) {
if (is_uploaded_file($_FILES['image']['tmp_name'])) {
$conn = mysqli_connect('localhost', 'username', 'password', 'databasename');
$imgData = addslashes(file_get_contents($_FILES['image']['tmp_name']));
$imageProperties = getimageSize($_FILES['image']['tmp_name']);
$sql = "INSERT INTO upload(image) VALUES('$imgData')";
$current_id = mysqli_query($conn, $sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysqli_error($conn));
if (isset($current_id)) {
echo 'done';
}
}
}
And then get data using base64
$sql = "SELECT * FROM upload WHERE id = 113";
$sth = $conn->query($sql);
$result = mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,' . base64_encode($result['image']) . '"/>';
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);
}
?>
I'm trying to insert LONGBLOBs to my database. Unfortunately when I click insert nothing is being inserted in the db. When I change the column type to BLOB everything is fine but the blob size capacityis too small so I really need LONGBLOBs. Using blob I can add only a 64kb file. Using longblob I can insert a file which is much larger. What's why I need to use LONGBLOB. I'm using MySQLi and PHP. Could you help me out?
if($_POST && $_FILES['uploadFile']['size'] > 0) {
$name = $_FILES['uploadFile']['name'];
$_SESSION['fileType'] = $_FILES['uploadFile']['type'];
$data = $_FILES['uploadFile']['tmp_name'];
//$data = addslashes($data);
$ifImage = getimageSize($_FILES['uploadFile']['tmp_name']);
$getAuthorID = $_SESSION['userID'];
$_SESSION['ifImage'] = $ifImage;
echo '<pre>'.print_r($_SESSION['ifImage'], true).'</pre>';
$fp = fopen($data, 'rw');
$content = fread($fp, filesize($data));
$content = addslashes($content);
fclose($fp);
/* SELECT FILE ID BY IT'S NAME */
$selectIDname= "SELECT fileID FROM files WHERE fileName = '$name'";
$selectIDnameQuery = mysqli_query($connection, $selectIDname);
$row = mysqli_fetch_array($selectIDnameQuery);
$selectIDname = $row['fileID'];
echo '<pre>ID: '.print_r($selectIDname, true).'</pre>';
$_FILES['uploadFile']['fileID'] = $row['fileID'];
/* INCREMENT FILE ID */
$selectFileIDQuery = mysqli_query($connection, "SELECT fileID FROM filescontent ORDER BY fileID DESC LIMIT 1");
$fetchFileID = mysqli_fetch_assoc($selectFileIDQuery);
$incrementFileID = $fetchFileID['fileID'] + 1;
/* GET AND INCREMENT FILE VERSION */
$getVersionsObject = new File($_FILES['uploadFile']['fileID']);
$fetchVersions = $getVersionsObject->getVersions();
$fetchLastElement = end($fetchVersions);
$incrementVersion = $fetchLastElement + 1;
echo '<pre>Version: '.print_r($incrementVersion, true).'</pre>';
/* SELECT FILE NAME FROM DB */
$selectName = mysqli_query($connection, "SELECT fileName FROM files WHERE fileName='$name'");
$fetchName = mysqli_fetch_assoc($selectName);
$fetchName = $fetchName['fileName'];
if(!strcmp($name, $fetchName)){
echo 'The file exists <br>';
$insertIntoFilescontentObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFilescontent = $insertIntoFilescontentObject->uploadContentIntoFilescontentFileExist($selectIDname, $incrementVersion, $content, $getAuthorID);
}
else{
echo 'The file does not exist';
$insertIntoFilesObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFiles = $insertIntoFilesObject->uploadContentIntoFiles($incrementFileID, $name, $getAuthorID);
$insertIntoFilescontentObject = new File($_FILES['uploadFile']['fileID']);
$insertIntoFilescontent = $insertIntoFilescontentObject->uploadContentIntoFilescontentFileNotExist($incrementFileID, $incrementVersion, $content, $getAuthorID);
}
$mysqliErorr = mysqli_error($connection);
echo '<br>'.$mysqliErorr.'<br>';
//header("Location: listFiles.php");
}
else if($_POST && $_FILES['uploadFile']['size'] == 0) {
echo 'You have not chosen a file';
}
}