Reputation: 21
I am new to php and am trying to retrieve images from my MySQL database.
Upon running the below script, I get "Please check the ID!" message. Am I missing something?
CREATE TABLE tbl_images(
id tinyint( 3 ) unsigned NOT NULL AUTO_INCREMENT ,
image blob NOT NULL ,
PRIMARY KEY ( id )
)
<?php
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
# Connect to DB
$link = mysqli_connect("$host", "$username", "$password") or die("Could not connect: " . mysqli_error());
mysqli_select_db("$database") or die(mysqli_error());
# SQL Statement
$sql = "SELECT `image` FROM `tbl_images` WHERE id=" . mysqli_real_escape_string($_GET['id']) . ";";
$result = mysqli_query("$sql") or die("Invalid query: " . mysqli_error());
# Set header
header("Content-type: image/png");
echo mysqli_result($result, 0);
} else
echo 'Please check the ID!';
?>
Upvotes: 1
Views: 319
Reputation: 3414
Here is complete code -
CREATE TABLE IF NOT EXISTS `tbl_images` (
`id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
`image` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
PHP
<?php
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}
if(isset($_GET['id']) && is_numeric($_GET['id'])) {
# Connect to DB
$link = mysqli_connect("$host", "$username", "$password") or die("Could not connect: " . mysqli_error());
mysqli_select_db("$database") or die(mysqli_error());
# SQL Statement
$sql = "SELECT `image` FROM `tbl_images` WHERE id=" . mysqli_real_escape_string($_GET['id']) . ";";
$result = mysqli_query("$sql") or die("Invalid query: " . mysqli_error());
# Set header
$res1= mysqli_result($result, 0);
echo '<img src="data:image/png;base64,' . base64_encode($res1) . '" />';
} else
echo 'Please check the ID!';
?>
Upvotes: 0
Reputation: 3414
Make your url = http://www.domain.com?id=[YOUR_IMAGE_ID]
Pass the ?id=your_id querystring you will get the id with $_GET['id']
Remove the header("Content-type: image/png");
add this two line below your $result variable
$res1= mysqli_result($result, 0);
echo '<img src="data:image/png;base64,' . base64_encode($res1) . '" />';
I am also unable to find mysqli_result function in your above code. If you have not declare
Please use this-
function mysqli_result($res, $row, $field=0) {
$res->data_seek($row);
$datarow = $res->fetch_array();
return $datarow[$field];
}
Upvotes: 0
Reputation: 50650
So you are either not providing an ID, or you are providing an ID and it's not "numeric." Check the value of $_GET['id']
.
Upvotes: 3