I have searched high and low for many many hours for a week or two if not more on the interent in how to upload images to a database. I know some poeple may say its not recommended but I want to do it for a project that Im working on.
Im using a local server XAMPP
PHP Version 5.6.3 ---- Client API version mysqlnd 5.0.11
and inserting this image and it works
http://ctd-web.fr/blog/wp-content/uploads/2009/06/php.jpg
Heres how I insert the image into the database
<html>
<body>
<form action="lastimagetest.php" method="POST" enctype="multipart/form- data">
<input type="file" name="image"><input type="submit" name="submit" value="Upload">
</form>
<?php
if(isset($_POST['submit']))
{
TRY{
$pdo = new PDO('mysql:host=localhost;dbname=database;','root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
echo $e->getMessage();
die();
}
var_dump($pdo);
$imageName = ($_FILES["image"]["name"]);
$imageData = (file_get_contents($_FILES["image"]["tmp_name"]));
$imageType = ($_FILES["image"]["type"]);
if(substr($imageType,0,5) == "image")
{
TRY{
$results = $pdo->prepare("INSERT INTO cspposts (name, image, type)VALUES(?,?,?)");
$results->bindParam(1, $imageName);
$results->bindParam(2, $imageData, PDO::PARAM_LOB);
$results->bindParam(3, $imageType);
$results->execute();
}catch(PDOException $e){
exit('Database error. Sorry please try again later.');
}
echo "Working code";
}
else
{
echo "only images";
}
//print_r($_FILES["image"]);
}
?>
<br>
<img src="showimage.php?id=173">
</body>
</html>
I know id=173 is there and id 173 is in the database
This all works fine and inserts data into the table
The table in phpMyAdmin
id is an int - AUTO_INCREMENT name is varchar(50) image is longblob type is varchar(10)
I then try and get the image back from the database using the code
<?php
TRY{
$pdo = new PDO('mysql:host=localhost;dbname=database;','root');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(Exception $e){
echo $e->getMessage();
die();
}
if(isset($_GET['id']))
{
$id = ($_GET['id']);
$query = $pdo->prepare("SELECT * FROM cspposts WHERE id = ?");
$query->bindParam(1, $id)
$query->execute();
while($row = $query->fetch(PDO::FETCH_ASSOC)){
echo $row["image"];
}
header("content-type: image/jpeg");
}
else
{
echo"Error!";
}
?>
the result is just a broken image
please, please i hope someone can help me get the results.
Many thanks