How do i display images from my database? (php)
I have setup an image table in my database to store my images as blob type. My problem is that i do not know how to display the images in the db from my web search page. Anytime i enter a searh query, it will display the keyword & the image name but it will not display the image itself. rather it displays long sql codes.
Here are my php codes for Imagesearch.php;
<style type="text/css">
body {
background-color: #FFF;
}
</style>
<?php
//get data
$button = $_GET['submit'];
$search = $_GET['search'];
$x = "";
$construct = "";
if (!$button){
echo "You didint submit a keyword.";
}
else{
if (strlen($search)<=2) {
echo "Search term too short.";
}
else {
echo "You searched for <b>$search</b><hr size='1'>";
//connect to database
mysql_connect("localhost","root","");
mysql_select_db("searchengine");
//explode our search term
$search_exploded = explode(" ",$search);
foreach($search_exploded as $search_开发者_开发问答each) {
//constuct query
$x++;
if ($x==1) {
$construct .= "keywords LIKE '%$search_each%'";
}
else {
$construct .= " OR keywords LIKE '%$search_each%'";
}
}
//echo out construct
$construct = "SELECT * FROM images WHERE $construct";
$run = mysql_query($construct) or die(mysql_error());
$foundnum = mysql_num_rows($run);
if ($foundnum==0) {
echo "No results found.";
}
else {
echo "$foundnum results found!<p>";
while ($runrows = mysql_fetch_assoc($run)) {
//get data
$name = $runrows['name'];
$image = $runrows['image'];
echo "
<b>$name</b><br>
$image<br>
";
}
}
}
}
You should have used Google... Link
You need a separate php script that will return the image itself, and then you will need to call that from your PHP script.
The other PHP script needs to set the Content-type header to the proper mime type.
You should make another script, at another URL, that accepts an ID through a get parameter to output the image. Could then do something along the lines of:
<?php
// ..your MySQL stuff
function error() {
echo "There was an error";
}
if (isset($_GET['id']) && is_numeric($_GET['id'])) {
$id = (int) $_GET['id'];
$sql = "SELECT * FROM images WHERE id = '$id'";
$query = mysql_query($sql, $conn);
if (mysql_num_rows() == 1) {
$data = mysql_fetch_assoc($query);
// Change this to the correct image type for your stored data
header("Content-type: image/gif");
echo $data['image'];
} else {
error();
}
} else {
error();
}
You'd then echo:
echo "<b>$name</b> <img src='theimagescript.php?id={$id}' alt='Image of $name' />";
精彩评论