How to upload images into MySQL database using PHP code
Firstly, you should check if your image column is BLOB type!
I don't know anything about your SQL table, but if I'll try to make my own as an example.
We got fields id
(int), image
(blob) and image_name
(varchar(64)).
So the code should look like this (assume ID is always '1' and let's use this mysql_query):
$image = addslashes(file_get_contents($_FILES['image']['tmp_name'])); //SQL Injection defence!
$image_name = addslashes($_FILES['image']['name']);
$sql = "INSERT INTO `product_images` (`id`, `image`, `image_name`) VALUES ('1', '{$image}', '{$image_name}')";
if (!mysql_query($sql)) { // Error handling
echo "Something went wrong! :(";
}
You are doing it wrong in many ways. Don't use mysql functions - they are deprecated! Use PDO or MySQLi. You should also think about storing files locations on disk. Using MySQL for storing images is thought to be Bad Idea™. Handling SQL table with big data like images can be problematic.
Also your HTML form is out of standards. It should look like this:
<form action="insert_product.php" method="POST" enctype="multipart/form-data">
<label>File: </label><input type="file" name="image" />
<input type="submit" />
</form>
Sidenote:
When dealing with files and storing them as a BLOB, the data must be escaped using mysql_real_escape_string()
, otherwise it will result in a syntax error.
Upload Multiple Images with PHP and put it into MYSQL Database
Slug is saving as an array, because it is an array.
$slug = $_POST['slug'];
should solve your problem, assuming the slug elements are added in the same order as your files.
As per the comments, the above PHP has been fixed and the fixed HTML below - all I did was remove the array directive from the input:
<form method="POST" action="action-add-images.php" enctype="multipart/form-data">
<input type="hidden" name="slug" value="<?php echo $_GET['slug']; ?>">
<label>Upload Files</label>
<input required type="file" name="image[]" class="form-control-file" multiple>
<button type="submit" class="btn btn-block btn-primary my-3 ">Upload Images</button>
How do i upload an image to my mysql database with php?
You don't need to store image directly into to database. Just store the image name in the database and fetch it when you want to show.
For e.g.
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = 0;
}
}
// Check if file already exists
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = 0;
}
// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
// execute your insert query here
$sqlScript = "INSERT INTO form (image) VALUES ('".basename( $_FILES["fileToUpload"]["name"])."')";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
Upload image in MYSQL database & display it using PHP with Swift
Getting the image from the user
See http://php.net/manual/en/reserved.variables.files.php and http://php.net/manual/en/features.file-upload.php and friends for the datails of how to use $_FILES
to receive the uploaded.
Once you have the image in a variable, say $jpg
, do not use any text encode/decode functions; it will only mangle things. The different approaches below will say what to do to avoid tripping over 8-bit codes.
There are three ways to present the image, each is somewhat complex
Storing the image in the database; showing image inline
I have used this approach for thumbnails, but don't recommend for big images.
Store it in a MEDIUMBLOB
in a table, use bin2hex()
in PHP to turn the image into a string. Then use INSERT ... VALUES (UNHEX('...'))
to switch back to binary at the MySQL server side.
After reloading, have the referencing PHP say something like
$b64 = base64_encode($blob);
echo "<img src='data:image/jpeg;base64,$b64'/>";
Storing the image in the database; PHP script to generate image
I use this when I want to use PHP's "image*" functions to modify the image before displaying it. Since this is more involved than you probably need, I will only skim over what needs doing.
The html for the page would invoke another script, with whatever arguments you need:
<img src=modify.php?this=stuff&that=stuff>
Then in modify.php
, start with
header('Content-type: image/jpeg');
And end with this (assuming you are building a JPEG):
imagejpeg($im);
Storing the image in a file
This is the preferred way that most of the big web sites do it most of the time.
If your file comes from an upload, then something like this moves it to a better path without having to touch the jpg.
$tmpfile = $_FILES['userfile']['tmp_name'];
move_uploaded_file($tmpfile, $uploadfile);
More info and examples: http://php.net/manual/en/function.move-uploaded-file.php
In the HTML, simply generate something like this:
<img src=path/to/file>
Do some research on where in your server's path you can put images, and make sure the permissions are adequate.
Note: The database is not involved in holding the image, instead it has a column for holding the url "path/to/file"
:
image VARCHAR(255) NOT NULL
For further discussion
- Which of the 3 techniques would you like to dig deeper into?
- Let's see the HTML you are generating.
- Let's see
SHOW CREATE TABLE
.
Multiple Upload Images into Mysql Database
You can either add 3 inputs
<td rowspan="1">
<input type="file" id="upload" name="images1[]">
</td>
<td rowspan="1">
<input type="file" id="upload" name="images1[]">
</td>
<td rowspan="1">
<input type="file" id="upload" name="images1[]">
</td>
Or make your one input allow multiple
inputs
<td rowspan="1">
<input type="file" id="upload" multiple name="images1[]">
</td>
Either way you will then get a $_FILES['images1']
that is now an array
Then your PHP code just needs to loop over the $_FILES array
<?php
include("koneksi.php");
if(isset($_POST['Input'])) {
$Kode = $_POST['Kode'];
$Tipe = $_POST['Tipe'];
// you should really be checking for upload errors
foreach ($_FILES['images1']['error'] as $err) {
switch ($err) {
case UPLOAD_ERR_NO_FILE:
echo 'No file sent.';
exit;
case UPLOAD_ERR_INI_SIZE:
case UPLOAD_ERR_FORM_SIZE:
echo 'Exceeded filesize limit.';
exit;
}
}
for($x=0; $x<count($_FILES['images1']['tmp_name']); $x++ ) {
$file_name = $_FILES['images1']['name'][$x];
$file_size = $_FILES['images1']['size'][$x];
$file_tmp = $_FILES['images1']['tmp_name'][$x];
$t = explode(".", $file_name);
$t1 = end($t);
$file_ext = strtolower(end($t));
$ext_boleh = array("jpg", "jpeg", "png", "gif", "bmp");
if(in_array($file_ext, $ext_boleh)) {
$sumber = $file_tmp;
$tujuan = "images/" . $file_name;
move_uploaded_file($sumber, $tujuan);
$sql = "insert into database_latihan values ('$Kode' , '$Tipe' , '$tujuan')";
mysqli_query($koneksi, $sql);
}else {
echo "Only Images can be store!";
}
} // endfor
}
?>
Upload image and save form data into a Mysql db using php
First replace ctype="multipart/form-data"
with enctype="multipart/form-data"
if(!empty($file_name)){
if(move_uploaded_file($file_tmp_name,"images/".$file_name))
echo "image uploaded";
else echo "image not uploaded";
}
Related Topics
Pdo Valid Characters For Placeholders
"Invalid Parameter Number: Parameter Was Not Defined" Inserting Data
How to Detect Search Engine Bots With PHP
Getting the Names of All Files in a Directory With PHP
Execute PHP Script in Cron Job
Laravel 5.5 Ajax Call 419 (Unknown Status)
PHP Function to Get the Subdomain of a Url
What Does It Mean to Escape a String
How to Initialize Static Variables
Laravel 5 Pdoexception Could Not Find Driver
Redraw Google Chart Based on User Input Via Ajax Request
Laravel 5.2 Validation Error Not Appearing in Blade
Remove New Lines from String and Replace With One Empty Space
Running MySQL *.SQL Files in PHP
PHP Simplexml How to Save the File in a Formatted Way