I want to load image, but the solution that I can get so far is loading a separate script with db - reconnection.
I have a init.php file which basically start up the application with db connection.
looks something like this.
if(!isset($_SESSION)){
session_start();
}
//error_reporting(0); //dont show path name errors when error occurs
// include required files
require 'databases/connect.php';
I have this line of code which tells the blob script to retrieve image Data
<img src="../core/functions/images.php?image_id=<?php echo $responses[$i]['product_id']; ?>" height="150" width="180" alt=""/>
And this is the problem script that re-connect db again and then retrieve the image data. If I do not reconnect the db, the mysql script will fail. Any help on this, so I don't need to reconnect db?
$connect_error = "Sry, we are working on an error, try later";
mysql_connect('localhost','root','') or die($connect_error);
mysql_select_db('SJ3') or die($connect_error);
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_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["imageData"];
}
?>
Related
I have PHP code that I am trying to delete the image from the database and uploads folder as well. I have researched and it seems
like I need the unlink option but I don't know enough about PHP or
coding on how to implement it. The code I have will delete from the
MySQL database just fine but when I try to add the uplink code it
breaks it and doesn't do anything.
I have tried adding in the following:
$file_path = 'uploads/' . $_POST["images"];
if(unlink($file_path))
to the code below.
//start PHP session
session_start();
if (!isset($_SESSION['success']))
{
header("Location: login_page.php");
die();
}
// check if value was posted
if($_POST){
// include database and object file
include_once 'config/database.php';
$file_path = 'uploads/' . $_POST["image"];
if(unlink($file_path))
{
// delete query
$query = "DELETE FROM dhospital WHERE id = ?";
$stmt = $con->prepare($query);
$stmt->bindParam(1, $_POST['object_id']);
}
if($stmt->execute()){
// redirect to read records page and
// tell the user record was deleted
echo "Record was deleted.";
}else{
echo "Unable to delete record.";
}
}
I am using PHP - PDO - MySQL
After I managed it to insert blobs into my db I'm trying to Display a BLOB from MySQL.
This is the getImage.php:
<?php
$id = $_GET['id'];
// do some validation here to ensure id is safe
$link = mysql_connect("localhost", "root", "root");
mysql_select_db("user_auth_tutorial");
$sql = "SELECT image FROM testblob WHERE image_id='$id''";
$result = mysql_query("$sql");
$row = mysql_fetch_assoc($result);
mysql_close($link);
header("Content-type: image/jpeg");
echo $row['image'];
?>
Here the HTML:
<img src="getImage.php?id=1" width="200" height="200" />
This is the content of my db:
Unfortunately Dev-Tools throw an internal server 500 Error.
Browser-Output:
Can anybody tell me what I do wrong?
Thank you so much!
try this
echo '<img src="data:image/jpeg;base64,'.base64_encode($row['image']).'"/>';
I am trying to store images into a path and then upload them into my database. The DB is called "store" and the table I'm using is called "images" containing 3 fields: id, name (varchar), image (longblob). The form is the following:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Upload an Image</title>
</head>
<body>
<form action="upload_file.php" method="POST" enctype="multipart/form-data" >
<input type="hidden" name="MAX_FILE_SIZE" value="262144000" />
<p>File:</p>
<input type="file" name="image" accept="image/jpeg" accept="image/jpg" accept="image/png" accept="image/gif">
<input type="submit" value="Upload" name="submit" />
</form>
</body>
</html>
The upload_file.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
//file properties
$file = $_FILES['image']['tmp_name'];
if(!isset($file)){
echo "<p>Please select an image.</p>";
} else {
//$image = mysql_real_escape_string(file_get_contents($_FILES['image']['tmp_name']));
$image = base64_encode(file_get_contents($_FILES['image']['tmp_name']));
$image_name = mysql_real_escape_string($_FILES['image']['name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size == FALSE){
echo "<p>Sorry, this is not an image.</p>";
} else {
echo "<p>File is an image. Processing...</p>";
if(!$insert = mysql_query("INSERT INTO images VALUES('','$image_name','$image')")){
echo "<p>Problem uploading image:".mysql_error()."</p>";
} else {
$lastid = mysql_insert_id();
echo "<p>Success!</p>";
echo "<img src=get.php?id=$lastid>";
}
}
}
error_reporting(-1);
?>
And get.php is:
<?php
//Connect to database
$conn=mysql_connect("localhost","root","my_password");
if(!$conn){
die("Could not connect to MySQL");
}
if(!mysql_select_db("store")){
die("Could not open database:".mysql_error());
}
$id = $_REQUEST['id'];
$image = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_array($image);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
?>
The images are uploaded, but are not shown. Instead, I get a broken image icon, and I don't understand why. Can someone help me??
Try to solve this problem step by step
This process can be identified as three parts and split up quickly. The HTML form, the PHP upload and saving to database process, and the loading from database process.
Try echoing the image data before inserting it into the database to see if the data is actually correct.
Update the database and see if the data is inserted there.
Load the image data from the database and echo it to see if it loads it correctly.
Try the full script.
This is just an example checklist. But you can change this and add more steps to it.
Also, please consider updating to MySQLi. You are using deprecated functions which could lead to security issues. Many information sources regarding this subject can be found on the web.
Correct the get.php code with this code
<?php
//Connect to database
$conn = mysql_connect("localhost", "tester", "");
if (!$conn) {
die("Could not connect to MySQL");
}
if (!mysql_select_db("tester")) {
die("Could not open database:" . mysql_error());
}
$id = $_REQUEST['id'];
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
$image = $image['image'];
header('Content-type: image/jpg');
echo base64_decode($image);
You have to change the database name and user whit your own
These are the parts that i have changed:
$rows = mysql_query("SELECT * FROM images WHERE id=$id");
$image = mysql_fetch_assoc($rows);
echo base64_decode($image);
I was trying to view a PDF from my a MySQL database but it gets stuck on loading.
Here's my code:
<?php
header("Content-type: application/pdf");
$con = mysqli_connect("localhost","root","username","password");
//check if errors occur in connection to database
if (mysqli_connect_errno())
{
//return the error
echo mysqli_connect_error();
}
$filename = $row['name'];
$query = "SELECT content from images WHERE id = 7";
$result = mysqli_query($query,$con)or die(mysqli_error());
$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
echo $row['content'];
?>
You can use dompdf or TCP pdf library for better and extended functionality.
or try to use ob_clean() method in starting of the line.
or remove first header("Content-type: application/pdf"); and check whether query is working or not.
I have managed to upload a video (<2MB) to my table as a LONGBLOB type. The table name is test2 in database 'test'. But i cant play an mp4 video. This is my code.
<?php
echo 'h';
$arr=array();
$con=mysql_connect('localhost','root','46');
mysql_select_db('test',$con);
$query="select video from test2";
$result=mysql_query($query,$con);
$arr=mysql_fetch_array($result);
header('content-type: video/mp4');
echo $arr[0];
?>
Thanks.
You shouldn'd be fetching the whole video into memory from the database at once, because it will stay in memory the whole time while the client is playing/downloading it. With more concurrent users, every PHP backend will keep its own copy of the video in memory. This will make your server run out of memory pretty quickly.
You could use substr() in the SQL query to fetch it in chunks, but that would put more load on the database. Better to split it in chunks before inserting it to the database.
Or, you know, just serve it directly from the file system with Apache (or any web server), like $deity intended.
I stumbled on this question in my search for similar.
If you want to not use header and play in a div or other html container from a sql blob do this:
function displayvideo(){
global $db_user, $db_password, $media_db_name, $db_host;
$video = "some_video.mp4";
$dbconnect = 'mysql:dbname='.$media_db_name.';host='.$db_host.'';
try {
$db = new PDO($dbconnect, $db_user, $db_password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
if (($result = $db->query('SELECT video FROM videos WHERE `name` = "'.$video.'"')) !== false) {
echo '<div content="Content-Type: video/mp4">
<video width="700" height="450" controls="controls" poster="image" preload="metadata">
<source src="data:video/mp4;base64,'.base64_encode($result->fetch(PDO::FETCH_COLUMN)).'"/>;
</video>
</div>';
} else {
// actions to take if it fails
}
}
In case you really want to store videos as databases blobs (I don't recommend so), this should work:
<?php
mysql_connect('localhost', 'root', '46') or die('Could not connect to MySQL server');
mysql_select_db('test') or die('Could not select database');
if (($result = mysql_query('SELECT video FROM test2')) !== false) {
header('Content-Type: video/mp4');
print mysql_result($result, 0);
} else {
// actions to take if it fails
}
Even better you might want to use PDO to query the database:
<?php
$db = new PDO('mysql:host=127.0.0.1;dbname=test', 'root', '46');
if (($result = $db->query('SELECT video FROM test2')) !== false) {
header('Content-Type: video/mp4');
print $result->fetch(PDO::FETCH_COLUMN);
} else {
// actions to take if it fails
}