I have tried to download images to a directory but now I want to save the images to the database using BLOB type by not using the File Chooser. I mean save the images direct from a URL:
Say:
http://someserver.com/images/imageone.gif
How can I save that directly to database? Do I have to download it first before saving to database? Please help me..
Like you would save any other data.
$imageContents = file_get_contents('http://someserver.com/images/imageone.gif');
$imageContentsEscaped = mysql_real_escape_string($imageContents, $link);
mysql_query("INSERT INTO table_name (imageData) VALUES ('$imageContentsEscaped')", $link);
Make sure the column you want to save the image data to is set to a binary type such as BLOB.
// download image to memory
$image = file_get_contents('http://example.com/my/image.jpg');
// open PDO connection
$db = ...;
// insert downloaded data to the DB
$sql = 'insert into my_table(filename, content) values (?,?)';
$stmt = $db->prepare($sql);
$stmt->bindParam(1, 'my/image.jpg');
$stmt->bindParam(2, $image, PDO::PARAM_LOB);
$stmt->execute();
Related
I want to upload the image to this folder called roomPhoto. Then from there i want the sql server database name imagepath to store the path instead of the image itself. Can someone help me with this?
session_start();
include "../../lib/mssql.connect.php";
$target = "roomPhoto/";
$target = $target . basename( $_FILES['photo']['imagepath']);
$params = array($_POST['xone'],$_POST['yone'], $_POST['xtwo'], $_POST['ytwo'], $_POST['venue'] , $_POST['description'] , $_POST['roomlevel'], ( $_FILES['photo']['imagepath']));
$sql = "INSERT INTO map(x1, y1, x2, y2, venue, description, roomLevel, imagepath)
VALUES (?,?,?,?,?,?,?,?)";
$result = sqlsrv_query($conn, $sql, $params);
echo "Account had been successfully created";
I suggest you to not store image in database.
This is comment but i am not able for that.
Efficient way to do is:
Only save image name in database and upload image in specific folder using move_uploaded_file.
For display image, you will get image name from query...append that in your folder path and just set it to
<img src="PATH_HERE">
I am trying to use PDO to display image stored in a sql server database in a varbinary(max) field.
$conp = sqlsrv_connect("localhost", array("database"=>"dbname", "UID"=>"uid", "PWD"=>"somepassword"));
$id=16;
$stmt = sqlsrv_query($conp, "select image from image_tbl where id = $id");
$getAsType = SQLSRV_PHPTYPE_STREAM(SQLSRV_ENC_BINARY);
if (sqlsrv_fetch( $stmt ))
{
$image = sqlsrv_get_field( $stmt, 0, $getAsType);
header("Content-type:image/jpeg;");
fpassthru($image)
}
the above code displays the image correctly. If I try to use PDO as follows it shows a broken image icon.
$sql = "SELECT image FROM image_tbl WHERE id = ?";
$stmt = $conp->prepare($sql);
$stmt->execute(array(&$_GET['id']));
$stmt->bindColumn(1, $image, PDO::PARAM_LOB, 0, PDO::SQLSRV_ENCODING_BINARY);
$stmt->fetch(PDO::FETCH_BOUND);
header("Content-type:image/jpeg;");
echo $image;
without the header information it shows the same data. what am I doing wrong?
UPDATE: when I put file_put_contents('test.jpg', $data); it stores the image correctly. But I still cannot show it on the browser. May be there is something to do with the content-type. Don't know.
EDIT: I have changed the print_r($image); with echo $image;.
I'm very new to development, and I'm trying to retrieve an image from an SQL server over an odbc connection using the below:
<?php
require ('connect.inc.php');
$sql = "SELECt image FROM test.dbo.clients WHERE id = 1";
$sql_exec = odbc_exec($con, $sql);
if($sql_array = odbc_fetch_array($sql_exec)){
$image = base64_encode($sql_array['image']);
header('Content-type: image/jpeg');
echo "<img src=".$image."/>";
}
?>
The issue is that I'm getting an icon showing a broken image.
The query is correct as when I change it to the code below, it returns this string instead of the image:
Q2hyeXNhbnRoZW11bS5qcGc=
<?php
require ('connect.inc.php');
$sql = "SELECt image FROM test.dbo.clients WHERE id = 1";
$sql_exec = odbc_exec($con, $sql);
if($sql_array = odbc_fetch_array($sql_exec)){
$image = base64_encode($sql_array['image']);
echo $image;
}
?>
I know the code is not correct and might be vulenrable to SQL injection, however I'd appreciate if you can help me retrieve the image.
Many thanks in advance,
J
If you decode the base64 string you get, then you'll see that the decoded data is Chrysanthemum.jpg. This is just the filename of the image, not the image data.
You need to either store the image in the database (not the filename) or add some code to read the image from the filesystem.
BTW, Content-Type image/jpeg requires that the data is the raw image, but your content (<img src=...> ...</img>) is an HTML fragment.
I have successfully added the original image into my imgs/ folder and also onto the server. But I'm wanting to add the thumbnail into the database. I've added it into the imgs/ folder but can't seem to find away to insert it into the database.
This is the final bit of code that is used to crop the img and insert it to the folder.
I need to insert it into the database also so I can call on it for the $_SESSION User and the Users friend as I have profiles.
if (isset($_POST["upload_thumbnail"]) && strlen($large_photo_exists)>0) {
//Get the new coordinates to crop the image.
$x1 = $_POST["x1"];
$y1 = $_POST["y1"];
$x2 = $_POST["x2"];
$y2 = $_POST["y2"];
$w = $_POST["w"];
$h = $_POST["h"];
//Scale the image to the thumb_width set above
$scale = $thumb_width/$w;
$cropped = resizeThumbnailImage($thumb_image_location, $large_image_location,$w,$h,$x1,$y1,$scale);
//Reload the page again to view the thumbnail
header("location:".$_SERVER["PHP_SELF"]);
exit();
}
if(isset($_GET['a'])){
if ($_GET['a']=="delete"){
if (file_exists($large_image_location)) {
unlink($large_image_location);
}
if (file_exists($thumb_image_location)) {
unlink($thumb_image_location);
$creator_id = $_SESSION['id'];
$sql = "UPDATE users SET user_pic_small='".$img."' WHERE id=$creator_id";
$sql2 = "INSERT INTO userphotos(photo_ownerid,photo_ispublic, photo_name, photo_caption, photo_imagedata) VALUES ($creator_id,1,'Profile Picture','Profile Picture','$img')";
// insert the image
if(!mysql_query($sql)) {
echo "Fail. It broke.";
}else{
$c=mysql_query($sql2);
echo "<script> parent.alert('Image Uploaded','',1000);</script>";
}
}
}
}
Hope someone can help. Thanks.
If you want to add in your database the path of thumbnail ($thumb_image_location), just add the code that inserts the path before unlink().
If you want to store the whole image into database, you need the column to be MEDIUMBLOB type, then, before unlink() read the code of the file that contains the image, for example with:
$img = file_get_contents($thumb_image_location);
Then, INSERT data stored in $img into your database.
Ideally, you don't want to be adding the thumbnail itself to the database, just a reference (filepath) to the file. So, while I don't know what your database looks like, you need to go through the following steps:
Create a field in your table called 'thumbnail' or similar. This will hold the name which the thumbnail file is saved as.
Add the filepath to the database immediately after you crop the large image (ie between the lines '$cropped = ...' and 'header("location....' in your code)
Whenever a user or user's friend is logged in, check this field and pull any thumbnail images referenced in the table.
And that is basically it.
If you want to store only the path of the Image into Database ,than it's fine to insert only the path and serve it with HTML.
Otherwise if you want to store the raw data of the image into Database than you have to encode the Image into base64 String .
Sending/Displaying a base64 encoded Image - Here is how you encode and image at base64.
And store this huge string into a Blob Field Type into databse.
You can use this:
// Read the file
$fp = fopen($file, 'r');
$data = fread($fp, filesize($file));
$data = addslashes($data);
fclose($fp);
// Create the query and insert into our database.
// image is an BLOB field type
$query = "INSERT INTO tbl_images ";
$query .= "(image) VALUES ('$data')";
$results = mysql_query($query, $link);
I want to insert a image in blob format to db.
how to write a program in zend framework.
a simple form
just choose one image and insert into db.
In your Zend form create a file element:
$element = new Zend_Form_Element_File('fileElement');
Then you can insert the uploaded image to your DB in BLOB format like this:
$conn = new PDO("mysql:host='host';dbname='database'", 'userName', 'password');
$imagePath = $zendForm->fileElement->getFileName();
$image = file_get_contents('$imagePath');
$sql = "INSERT INTO images (data) values(?)";
$q = $conn->prepare($sql);
$q->bindParam(1, $image, PDO::PARAM_LOB);
$q->execute();
Read it in as a string using file_get_contents and store that.
That said, it is seldom a good idea to store the actual image data in the database. It is better practice to generate a unique filename and store that in the DB instead.
Here is some code to save the file in zend:
// This is to save in saveAction()
$source = $this->view->form->upload->getFileName();
$fp = fopen($source,'r');
$content = fread($fp,filesize($source));
// I don't use addslashes, because i already have that in my mapper
fclose($fp);
$model->image = base64_encode($content);
// Save here
// This is to read in imagesAction()
$this->_helper->Layout()->disableLayout();
$this->_helper->ViewRenderer->setNeverRender();
header('Content-Type: image/gif');
echo base64_decode($image);
exit;
I had alot of problems with it, try to make your save work and don't insert it into the database directly to test the reading. This won't make it possible unless you know the correct db encoding (which i don't).