From iOS app to php script, I want to store a bench of images as BLOB types:
$profile_images = $_REQUEST['profile_images_array'];//get the array of images
//loop the images and store them one by one
foreach($profile_images as $image){
$sqlinsertimages = "insert into profile_images (id_client,image) Values ('".$id."',mysql_real_escape_string('".$image."'))";
$result = mysql_query($sqlinsertimages);
}
The insert would work fine if I eliminate the image field (which is BLOB type), so the issue is obviously with the saving BLOB types in the table.
How to store properly the images in PHP as BLOB?
PS: not willing to adopt the file system storage.
Ok, I guess that work finally, didn't knew that I had to save the image to the server before saving it to MySQL:
foreach($profile_images as $image){
//Get the file as a string before inserting it to table
$content = file_get_contents($image);
$content = mysql_real_escape_string($content);
$sqlinsertimages = "insert into profile_images (id_client,image) Values ('".$id."','".$content."')";
$result = mysql_query($sqlinsertimages);
}
Related
My DB developer made me a db with a field in the SQL table as image type.
I am trying to take the image someone uploads and just insert it in.
$imagePath = Input::file('image');
$image = $imagePath->getPathName();
$image returns the temp path name
$file = fopen($image, "rb");
$content = fread($file, filesize($image));
fclose($file);
$SqlConn = "INSERT INTO [poll14] ([image]) VALUES ($content)";
But I get this error: An error occurred substituting the named parameters.
How am I supposed to be inserting the data in?
Try this, which is similar to your requirement here
insert into poll14 (ImageColumn)
SELECT BulkColumn
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img
I'm pretty new to PHP. I hate to have to ask questions, because I'm sure this is documented somewhere, but after looking for a while, I just cannot seem to put two and two together.
I have a program that will allow multiple images to be uploaded to an item within the database. Basically, for each item in the database, there might be multiple image uploads.
Example:
Item: Xbox 360
Images:
Xbox360.jpg
side.jpg
front.jpg
The image and item information is all stored in the database (MySQL), but the images are stored within the filesystem, and the database points to the URL of the image(s) in the filesystem.
The problem I'm having is that everything works as expected, except it allows duplicate image names to be written to the database. It doesn't allow duplicate images to be written to the filesystem, which I'm happy with. I want to make sure that the name of an image is only added once to the database. If the image name is a duplicate to another, it needs to not write to the database.
add_db.php:
$uniqueDir = uniqid();
$directory = "img/$uniqueDir/";
db_addItem($id_category, $name, $cost, $description, $qty, $directory); //Adds to the `items` table
foreach ($_FILES['i_file']['name'] as $filename) {
if ($filename != '' && $filename != 'No file chosen') {
//I think above is where I check for unique image names
$url = "img/$uniqueDir/$filename";
db_addImg($url, $filename); //Adds to the `img` table
$item_picsID = get_item_PicsID($filename, $url);
$itemID = get_itemID($directory);
db_insertImg($itemID, $item_picsID);
}
}
addFilesystem($directory); //Writes image(s) to filesystem
function db_addImg($url, $filename) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO img (`name`, `url`) VALUES(:filename, :url)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':filename' => $filename,
':url' => $url
));
}
function db_insertImg($itemID, $item_picsID) {
include 'mysql_login_pdo.php';
// Create the SQL query
$query = "INSERT INTO `item_pics` (`item_id`, `img_id`) VALUES(:itemID, :item_picsID)";
$stmt = $db->prepare($query);
$stmt->execute(array(
':itemID' => $itemID,
':item_picsID' => $item_picsID
));
$db = null;
return;
}
Everything works, except it will write duplicate image names to the database. I want the image names to be distinct. I also don't want to rename the images (if possible).
You can define an UNIQUE index on the name column in img table, and then use slightly modified INSERT statement in your db_addImg function:
function db_addImg($url, $filename) {
//...
$query = "INSERT INGORE INTO img (`name`, `url`) VALUES(:filename, :url)";
//...
}
It will quietly cancel any insert where the is a UNIQUE key collision, which will end up in distinct filenames across your img table.
I would use a filename based on the primary key from the img table as you're guaranteed it's unique.
Otherwise, you'll need to guess a unique filename with some type of hashing and then check the file system. All of which can be expensive operations.
Looks like you are using PDO, so the static method lastInsertId will get the last insert id (primary key).
For example:
// after your insert to img
$filename = 'img' . $db->lastInsertId() . $extension;
This will require changing the img table slightly. But you're better off storing meta data (file type, size, etc) in this table as opposed to the file location (as that can change).
I think better to use hash value of your url as the primary key. Be cause string searching is much slower as int.
I have a mysql blob field in which our team stored an image for every record. Now I want to download all images on my hard disk through php script. A prompt response will be appreciated.
Best Regards...
Aisha
$result=mysql_query("SELECT * FROM test WHERE 1");
while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$filename = rand(1, 100).'.txt';
file_put_contents('./'.$filename, $row['blob']);
}
This is working (tested).
It wil save the file under a random filename (1-100.txt).
You can change the filename by changing $filename.
And here is a simple sample MySQL-table with 2 demo files with content Test #1 and Test #2:
CREATE TABLE IF NOT EXISTS `test` (`blob` blob NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `test` (`blob`) VALUES(0x5468697320697320746573742023312e), (0x5468697320697320546573742023322e);
you can use file_put_contents,
fetch rows from your database and foreach row write blob/data to file
Error in Writing to Image file from PHP
http://php.net/manual/en/function.file-put-contents.php
You can try this also........
function save_file($file_id, $target_folder) {
$result = $DB->get_file($file_id);
$file_content = $result->fields['your_file_content_field'];
$name = $result->fields['name'];
/* Decode only if the file contents base64 encoded
* before inserting to database.
*/
$file_content = base64_decode($file_content);
return file_put_contents($target_folder.'/'.$name, $file_content);
}
I try to read image from database (blob) but i have problem becouse i don't know mime type of image. I have only tinyblob.
Can i read image and save it back to my hard disk?
The best solution is to store the mime-type in the DB at the same time you're inserting the image into the blob field. Otherwise you're going to have to the following EACH TIME the image is retrieved:
$image = $row['imageblob']; // $row = result row from DB query.
$finfo = new finfo(FILEINFO_MIME);
$mime_type = $finfo->buffer($image);
This gets to be expensive very quickly on a busy system, so best do the determination ONCE and then store that result.
Relevant PHP docs here.
Why not store the images on the hard disk all the time, and store in the Database a relative link based on a known directory?
Here's some code that I have used to get a logo (blob) from a mysql database
<img src="data:image/png;base64,<?php echo base64_encode($MyClass->getLogo())?>" alt="Logo" width="233" height="65" />
And the getLogo() function
public function getLogo()
{
if ($this->getId())
$query = "SELECT `logo` FROM Logos WHERE `logo_id` = '{$this->getId()}' LIMIT 1";
else
$query = "SELECT `logo` FROM Logos WHERE `logo_id` = '1' LIMIT 1";
$result = mysql_query($query);
if ($result)
$row = mysql_fetch_array($result);
else
return NULL;
return ($row['logo']);
}
I have some photos (not big, only 8kb) in mysql database (in my desktop). the field type is blob. i want to export the table to xml file then upload it to my database website. but it not success. Here is what i have done :
Exporting the data to xml (in my computer desktop):
FileStream fs = new FileStream(filename,FileMode.Create,FileAccess.Write,FileShare.None);
StreamWriter sw = new StreamWriter(fs,Encoding.ASCII);
ds.WriteXml(sw); //write the xml from the dataset ds
Then upload the xml from my joomla website. i load the xml before insert it to the database
...
$obj = simplexml_load($filename);
$cnt = count($obj->mydata); //mydata is the table name in the xml tag
for($i=0;$i<cnt;$i++)
{
...
$myphoto = 'NULL';
if(!empty($obj->mydata[$i]->myphoto))
{
$myphoto = base64_code($obj->mydata[$i]->myphoto);
}
//insert to the database
$sqlinsert = "insert into jos_myphoto (id,myphoto) values(".$i.",".$myphoto.")";
...
}
...
it keep telling me 'DB function failed'. when value of $myphoto is null, the query work well but if $myphoto is not null, the error appears. i think there is something wrong with the code
$myphoto = base64_code($obj->mydata[$i]->myphoto).
i try to remove base64_code function but it dont work. How to solve this problem? Sorry for my bad english
Your data may contain which needs escaping put mysql_real_escape_string() function and try
It is always a good habit to store data using this function which save you from sql injection also.
And put quotes around the column data.
$sqlinsert = "insert into jos_myphoto (id,myphoto)
values(".$i.",'".mysql_real_eascape_string($myphoto)."')";