I want to save gif type image in mySQL database without post method.
<form action="add_file.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaded_file"><br>
<input type="submit" value="Upload file">
</form>
I want to upload file by php code only. for example:
// Gather all required data
$name = $File_Name;
$mime = $File_Type;
$data = $File_Data;
$size = $File_Size;
// Create the SQL query
$query = "
INSERT INTO `file` (
`name`, `mime`, `size`, `data`, `created`
)
VALUES (
'{$name}', '{$mime}', {$size}, '{$data}', NOW()
)";
I have more then 21,0000 image in my local. I want to save image in loop.
Upload the files using FTP, then write a little PHP script that you run only once
that loops through the folder and adds the images to the database.
Make sure to remove the php file after it is done, so that you don't run it again accidentally ;)
Related
For security reasons I've decided that uploading user profile images to a database, rather than just a folder and uploading the image addresses, would be a good idea.
I've never dealt with file uploads in a backend before, but having read up about this from various sources, I believe that I'm doing everything correctly. However no useful binary data is being uploaded.
in php.ini
file_uploads=On
In the frontend
<form enctype="multipart/form-data" method="post" autocomplete="on" action="upload/">
<p>
<input type="file" id="avatar" name="avatar" accept="image/png, image/jpeg" required />
<label for="avatar">*Profile photo</label>
</p>
<p class="submitter two-thirds columns">
<input type="submit" value="Apply" />
</p>
</form>
In the backend
if(isset($_SESSION['id']))
$UserID = $_SESSION['id'];
else exit(1);
if (!empty($_FILES['avatar'])){
$photo = fopen($_FILES['avatar']["tmp_name"], 'rb');
$photo_mime = $_FILES['avatar']["type"];
}
else exit(1);
$values_data = array(
$UserID,
$photo,
$photo_mime,
);
$sql = "INSERT INTO `user`
(
UserID,
photo,
photo_mime
)
VALUES
(
:UserID,
:photo,
:photo_mime
)
ON DUPLICATE KEY UPDATE
photo = :photo,
photo_mime = :photo_mime
";
$sth = $dbh->prepare($sql);
$sth->bindValue(':UserID', $values_data[0]);
$sth->bindValue(':photo', $values_data[1]);
$sth->bindValue(':photo_mime', $values_data[2]);
$sth->execute();
And the database does get some information
However those image binaries are all 1KB. Looking inside them they have data that is like this
Resource id #13
So the binaries are getting messed up or dropped somewhere along the line... but where?
fopen() doesn't return the contents of the file. It returns a file pointer resource, which you then can pass to something like fread() to get the contents.
Something like:
$handler = fopen($_FILES['avatar']["tmp_name"], 'r');
$file = fread($handler, filesize($_FILES['avatar']["tmp_name"]));
fclose($handler);
An easier way would be to use file_get_contents():
$file = file_get_contents($_FILES['avatar']["tmp_name"]);
which will give you the contents in one line.
I tried to insert image from its path into mysql database using php and I did it but when I need to retrieve the image from mysql database into tag the image doesn't appear.
my database
CREATE TABLE IF NOT EXISTS `tbl_images` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` blob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
index.php
<?php
$connect = mysqli_connect("localhost", "root", "", "test");
if(isset($_POST["insert"]))
{
$path='C:\\xampp\\htdocs\\test_img\\4.jpg';
$query = "INSERT INTO tbl_images(name) VALUES ('LOAD_FILE($path)')";
if(mysqli_query($connect, $query))
{
echo '<script>alert("Image Inserted into Database")</script>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="submit" name="insert" id="insert" value="Insert" />
</form>
<table >
<?php
$query = "SELECT * FROM tbl_images ";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_array($result)) {
echo '
<tr>
<td> <img src="data:image/jpeg;base64,'.base64_encode($row['name'] ).'" height="200" width="200" /> </td>
</tr>
';
}
?>
</table>
</body>
</html>
Edit: the insert doesn't work correctly. it insert the string LOAD_FILE(C:xampphtdocs est_img4.jpg) instead of the image itself.
BLOB columns can only store 64KB of data, so any images larger than that, which is going to be most, will get truncated and can't be displayed.
You'll want to use LONGBLOB if you want to store these in the database.
You also can't insert using LOAD_FILE unless the file's present on the same server as the MySQL server process. This is not always the case. If it is present then you should be doing:
$stmt = $connect->prepare("INSERT INTO tbl_images(name) VALUES (LOAD_FILE(?))");
$stmt->bind_param('s', $path);
$stmt->execute();
Where the path is quoted, not the LOAD_FILE call itself. You're inserting a plain string and the literal text "LOAD_FILE(...)" is not valid image data.
Remember, storing images in the database is usually a bad idea. Store a reference to the image instead, like a file path or URL to an object-store.
You're also serving up images as inline data:base64 data which is extremely inefficient. Not only does it increase the amount of data required to transmit the image by about 33% but it means the images must be sent on each page load and cannot be cached. For mobile users this will burn through data fast.
I did a small form in HTML that allows you to add files and records everything in a database.
Everything works correctly when I save images, but when I try to save the PDF file type doesn't work.
Does anyone could tell me where I am failing?
Thank you all.
Code of Form
<tr><td>File:</td><td>
<input type="file" name="image" accept="image/jpeg, image/png, application/pdf" maxlength="200" title="Choose File" >
</td></tr>
PHP code to save in database
$image= addslashes(file_get_contents($_FILES["image"]["tmp_name"]));
$image_name = addslashes($_FILES['image']['tmp_name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size==FALSE)
echo "";
else{
$insert = "INSERT INTO table(name, date, image)
VALUES ('$name', curdate(), '$image')";
mysql_query($insert);
}
getimagesize() returns FALSE for non image files (eg pdf). Your insert was never executed.
$image = file_get_contents($_FILES['image']['tmp_name']);
$image = mysql_real_escape_string($image);
mysql_query("UPDATE ngc set pic='" . $image "' WHERE username='" . $_SESSION["username"] . "'");
<form method="post" action="" enctype="multipart/form-data">
Upload Image :<input type="file" name="image" id="file">
<br><input type="submit" name="submit" value="Update!" class="btnSubmit">
</form>
i want to upload image to database..
Read this very nice example here: http://www.mysqltutorial.org/php-mysql-blob/
Also see this image gallery example here: http://www.anyexample.com/programming/php/php_mysql_example__image_gallery_(blob_storage).xml
BLOBs are data types in MySql database which can help you store image files in database directly.
Although a better way would be to store the file on the disk and store the path of that variable in the database.
get the Content of the file and save in database;
$image = addslashes(file_get_contents($_FILES['image']['tmp_name']));
Mysql:
$sql = "INSERT INTO `product_images` (`id`, `image`) VALUES ('1', '{$image}')";
First of all if you want to save the entire image into the database , you must have the pic attribute type set to BLOB , here you have two options , either save the entire image into database , or save the name after uploading the images into a specified folder with a unique name each , so you can retrieve the images by name into this directory.
I was able to develop a code in enabling users to freely upload images, while the pictures would be stored to the MySql database. But I also would like to add to the php and mysql code image categories where before uploading the image, users can select from ether category- All, People, Cities, Nature and Others then click submit. How do I add that to my php code and mysql table? See my original code below:
<?php
$dbCnn = mysql_connect('', '', '');
mysql_select_db('', $dbCnn);
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = addslashes(file_get_contents($_FILES['file']['tmp_name']));
$insStr = "INSERT INTO imagedata(id, image) VALUES ('', '{$image}')";
mysql_query($insStr);
}
Don't store images in database because it's useless. Instead of this, store in database only path to file and file save on server.
So...
<form action="" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<select name="category">
<option>Nature</opton>
<option>People</option
</select>
</form>
<?php
if(isset($_POST['category']) && isset($_FILES['file']['tmp_name'])){
//mysql connect etc
move_uploaded_file($_FILES['file']['tmp_name'], path/where/to/save/file);
mysql_query("INSERT INTO table VALUES('{$_FILES['file']['name']}', '{$_POST['category']}')");
}