Load image from mysql DB – PHP

  php

Q(Question):

I store images using one of my web pages. Next I want to load image from the db and pass the value to ajax page. Other values got correctly. But didn’t get image.This is my code.


php page. When user click on select link It pass values to ajax page
echo "<td><a href='javascript:void(0);' onclick=\"test('$VehicleNo','$Year','$Other','Image'); return false;\">Select</td>";
This is my ajax code.
function LookupVehicle(VehicleNo,Year,Other,Image){
document.getElementById('VehicleNo').value=VehicleNo;
document.getElementById('userfile').value=Image;
document.getElementById('Year').value=Year;
document.getElementById('Other').value=Other;
}

Could someone help me?

A(Answer):

what does the variable $image contain?

A(Answer):

It has blob type of data. I’m inserting image like this.


<form enctype="multipart/form-data" action="insert.php" method="post" name="changer">
<input name="MAX_FILE_SIZE" value="102400" type="hidden">
<input name="image" accept="image/jpeg" type="file">
<input value="Submit" type="submit">
// Make sure the user actually
// selected and uploaded a file
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0) {
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
// Create the query and insert
// into our database.
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
// Print results
print "Thank you, your file has been uploaded.";
}
else {
print "No image selected/uploaded";
}
// Close our MySQL Link
mysql_close($link);
?>

A(Answer):

@ghjk

that explains it. do you know how HTML displays images?

A(Answer):

No. This is the first time I’m trying to load images from the DB.

A(Answer):

HTML (and thus Javascript) does not display images at all. it merely provides a link to the image, the remainder is left up to the browser software.

A(Answer):

found. We can load images like this.


$link = mysql_connect("localhost", "root", "xxx") or die("Could not connect: " . mysql_error());
// select our database
mysql_select_db("xxx") or die(mysql_error());
// get the image from the db
$sql = "SELECT Image FROM xxx WHERE Id=21";
// the result of the query
$result = mysql_query("$sql") or die("Invalid query: " . mysql_error());
// set the header for the image
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
// close the db link
mysql_close($link);

LEAVE A COMMENT