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"/>';
}
?>