I am trying to upload images to my database.
This is the form.
<form action='index.php' method='POST' enctype='multipart/form-data'>
<label>Change Profile Pic</label> <br>
<input type='file' name='image'> <input type='submit' name=submitpicture
value='Upload'>
</form>
This is the set of functions.
if(isset($_POST['submitpicture']))
{
$link = mysqli_connect('localhost','root','*****','*****');
$image = file_get_contents($_FILES['image']['tmp_name']);
$imagename = ($_FILES['image']['tmp_name']);
$image_size = getimagesize($_FILES['image']['tmp_name']);
if($image_size== false)
{
echo "This is not an image.";
}
else
{
if(!$link) //This links to my database.
{
echo "No link";
}
else
{
$picturedatabase = "INSERT INTO databaseimage ('name','image') VALUES ('name','$image')";
if(mysqli_query($link,$picturedatabase));
{
echo "Entered into database";
}
}
}
}
When I upload an image, I get echoed back "Entered into Database" but when I check my database there are no rows. What am I doing wrong?
Instead, set image like this:
$image= 'data:image/' . $type . ';base64,' . base64_encode(file_get_contents($_FILES['image']['tmp_name']));
Then, when you put it as an image src it will display the image. This also will reduce requests.
Related
How can i store and display the images in a MySQL database. Till now i have only written the code to get the images from the user and store them in a folder, the code that i wrote till now is:
HTML FILE
<input type="file" name="imageUpload" id="imageUpload">
PHP FILE
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";}
I found the answer, For those who are looking for the same thing here is how I did it.
You should not consider uploading images to the database instead you can store the name of the uploaded file in your database and then retrieve the file name and use it where ever you want to display the image.
HTML CODE
<input type="file" name="imageUpload" id="imageUpload">
PHP CODE
if(isset($_POST['submit'])) {
//Process the image that is uploaded by the user
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["imageUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
if (move_uploaded_file($_FILES["imageUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["imageUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
$image=basename( $_FILES["imageUpload"]["name"],".jpg"); // used to store the filename in a variable
//storind the data in your database
$query= "INSERT INTO items VALUES ('$id','$title','$description','$price','$value','$contact','$image')";
mysql_query($query);
require('heading.php');
echo "Your add has been submited, you will be redirected to your account page in 3 seconds....";
header( "Refresh:3; url=account.php", true, 303);
}
CODE TO DISPLAY THE IMAGE
while($row = mysql_fetch_row($result)) {
echo "<tr>";
echo "<td><img src='uploads/$row[6].jpg' height='150px' width='300px'></td>";
echo "</tr>\n";
}
if(isset($_POST['form1']))
{
try
{
$user=$_POST['username'];
$pass=$_POST['password'];
$email=$_POST['email'];
$roll=$_POST['roll'];
$class=$_POST['class'];
if(empty($user)) throw new Exception("Name can not empty");
if(empty($pass)) throw new Exception("Password can not empty");
if(empty($email)) throw new Exception("Email can not empty");
if(empty($roll)) throw new Exception("Roll can not empty");
if(empty($class)) throw new Exception("Class can not empty");
$statement=$db->prepare("show table status like 'tbl_std_info'");
$statement->execute();
$result=$statement->fetchAll();
foreach($result as $row)
$new_id=$row[10];
$up_file=$_FILES["image"]["name"];
$file_basename=substr($up_file, 0 , strripos($up_file, "."));
$file_ext=substr($up_file, strripos($up_file, "."));
$f1="$new_id".$file_ext;
if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
{
throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
}
move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);
$statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");
$statement->execute(array($user,$f1,$pass,$email,$roll,$class));
$success="Registration Successfully Completed";
echo $success;
}
catch(Exception $e)
{
$msg=$e->getMessage();
}
}
insert image zh
-while we insert image in database using insert query
$Image = $_FILES['Image']['name'];
if(!$Image)
{
$Image="";
}
else
{
$file_path = 'upload/';
$file_path = $file_path . basename( $_FILES['Image']['name']);
if(move_uploaded_file($_FILES['Image']['tmp_name'], $file_path))
{
}
}
<!--
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:rahulpatel541#gmail.com)
CREATE TABLE `images` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`image` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB ;
-->
<!-- this form is user to store images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />
<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>
<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
mysql_connect("", "", "") OR DIE (mysql_error());
mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
header("location:search.php");
}
//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
$name=$_POST['image_name'];
$email=$_POST['mail'];
$fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
}
// our sql query
$sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
mysql_query($sql) or die("Error in Query insert: " . mysql_error());
}
?>
<?php
//SEARCH.PHP PAGE
//connect to database.db name = images
mysql_connect("localhost", "root", "") OR DIE (mysql_error());
mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database
$msg="";
$sql="select * from images";
if(mysql_query($sql))
{
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$id=$row['id'];
$name=$row['name'];
$image=$row['image'];
$msg.= '<img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " /> ';
}
}
else
$msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>
I'm trying to allow an admin upload pictures of products in to the database, but I only want to store the link/url of the picture in the database and then store the uploaded file in a folder.
This is what I've got so far, and I keep getting "Sorry there was a problem uploading your file".
Here is the PHP code:
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, "$targetFolder" . $imgName)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
and the HTML form:
<form id="product_form" name="product_form" enctype="multipart/form-data" action="inventory_list.php" method="post">
<label for="product_image">Product Image*:</label> <input type="file" name="product_image"id="product_image"/>
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form
Use Sql Query Below.
$sql = "INSERT INTO products(`product_name`,`product_model`,`product_price`,`product_width`,`product_height`,`product_weight`,`product_quantity`,`product_category`,`product_subcategory`,`product_image`,`product_description`,`date_added`) VALUES('".$product_name."','".$product_model."','".$product_price."','".$product_width."','".$product_height."','".$product_weight."','".$product_quantity."', '".$product_category."', '".$product_subcategory."', '".$imgName."', '".$product_description."','".date("Y-m-d H:i:s")."')";
Also Change below line for upload image $imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); to $imgData = $_FILES["product_image"]["tmp_name"];
Try this Hope this helps.Not tested
<form id="product_form" name="product_form" enctype="multipart/form-data" method="post" action="" >
<label for="product_image">Product Image*:</label> <input type="file" name="product_image" id="product_image" />
</div>
<div>
<button name="add" id="add">Add Item</button>
</div>
</form>
PHP code :
<?php
if ($_FILES['product_image']['error'] == 0) { // checking the file for any errors
$imgName = mysql_real_escape_string($_FILES['product_image']['name']); //returns the name of the image and stores it in variable $imgName
$imgData = mysql_real_escape_string(file_get_contents($_FILES["product_image"]["tmp_name"])); // returns the content of the file and stores it in $imgData
$imgType = mysql_real_escape_string($_FILES["product_image"]["type"]); //returns image/whatever the image type is
$targetFolder = "ProductImages/"; //directory where images will be stored...
$targetFolder = $targetFolder . basename($imgName); //adds the image name to the directory
}
$sql = "INSERT INTO products " . "(product_name,product_model,product_price,product_width,product_height,product_weight,product_quantity,product_category,product_subcategory, product_image, product_description,date_added) " . "VALUES('$product_name','$product_model','$product_price','$product_width','$product_height','$product_weight','$product_quantity', '$product_category', '$product_subcategory', '$imgName', '$product_description', NOW())";
//echo $sql;
mysql_select_db('online_store');
$result = mysql_query($sql, $conn);
$itemResult = "";
if (!$result) {
die('Could not enter data: ' . mysql_error());
}
$itemResult = "Product has been added";
if (move_uploaded_file($imgData, $targetFolder)) { // writes/stores the image in the targetfolder->ProductImages
echo "The file " . basename($imgName) . "has been uploaded!";
} else {
echo "Sorry, there was a problem uploading your file!";
}
?>
First of all in HTML form action="post" is incorrect, the action attribute should contain a path. The method attribute should contain post or get like this: method="get" or method="post".
I need help in writing this code to upload and save uploaded image in data base.
File 1:
<?php
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
<iframeid="upload_target"name="upload_target"src="#"style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
File 2:
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$target_path="my/";
$result = 0;
$name=$_FILES['myfile']['name'];
$target_path = $target_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
list($width, $height, $type, $attr) = getimagesize($target_path);
echo "Image width " .$width;
echo "<BR>";
echo "Image height " .$height;
echo "<BR>";
echo "Image type " .$type;
echo "<BR>";
echo "Attribute " .$attr;
$result = 1;
}
// sleep(1);
$link=mysql_connect('localhost','root','');
if(!$link)
{die('you cannot connect to database...');}
$db=mysql_select_db('final');
if(!$db)die('smile');
if (isset($_FILES['myfile']) && $_FILES['myfile']['size'] > 0) {
// define the posted file into variables
$name = $_FILES['myfile']['name'];
$tmp_name = $_FILES['myfile']['tmp_name'];
$type = $_FILES['myfile']['type'];
$size = $_FILES['myfile']['size'];
// if your server has magic quotes turned off, add slashes manually
//if(!get_magic_quotes_gpc()){
//$name = addslashes($name);
//}
// open up the file and extract the data/content from it
$extract = fopen($tmp_name, 'r');
$content = fread($extract, filesize($tmp_name));
$content = addslashes($content);
fclose($extract);
// connect to the database
// the query that will add this to the database
$s=mysql_query("SET NAMES 'utf8'");
$sql = "INSERT INTO `final`.`products` (`Productcode`, `Productname`, `Price`,`Descriptionofgood`, `image`) VALUES ('','','','','".$target_path."') WHERE `products`.`Productcode`='1371' ";
$results = mysql_query($sql);
if(!$result)die('not');
}
?>
Technically, if it is a small project.
You should not store images files in "Database" ; rather only their link (you may not even need that). Image or any media files are stored on server along with your other files (html,css,php). Of course, you need to put them on a dedicated folder for it.
The reason for not storing on database : because they are meant for data retrieval only and more importantly they are of smaller size (bigger sizes do exist, i am speaking in case of a small project which requires least possible resources. Storing media files on database is just not efficient.
Looking at your code, i can tell you are trying to store the files on your server.
They have used a very simple script for uploading here . Try it on your localhost before trying on a server.
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) is incorrect.
It should be if(move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path))
Remove the #.
I have created three page for it
index.php (Form for uplad image)
upload.php (Save the image in upload folder and its path in database)
3.showimage.php (Show the images from database)
Database Structure
id int(4) auto increment - image varchar(100) - image_name varchar(50)
here is the code:
index.php
<form method="post" action="upload.php" enctype="multipart/form-data">
<label>Choose File to Upload:</label><br />
<input type="hidden" name="id" />
<input type="file" name="uploadimage" /><br />
<input type="submit" value="upload" />
</form>
uplad.php
<?php
$target_Folder = "upload/";
$uid = $_POST['id'];
$target_Path = $target_Folder.basename( $_FILES['uploadimage']['name'] );
$savepath = $target_Path.basename( $_FILES['uploadimage']['name'] );
$file_name = $_FILES['uploadimage']['name'];
if(file_exists('upload/'.$file_name))
{
echo "That File Already Exisit";
}
else
{
// Database
con=mysqli_connect("localhost","user_name","password","database_name"); //Change it if required
//Check Connection
if(mysqli_connect_errno())
{
echo "Failed to connect to database" . mysqli_connect_errno();
}
$sql = "INSERT INTO image (id,image, image_name)
VALUES ('','$target_Folder$file_name','$file_name') ";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "1 record added successfully in the database";
echo '<br />';
mysqli_close($con);
// Move the file into UPLOAD folder
move_uploaded_file( $_FILES['uploadimage']['tmp_name'], $target_Path );
echo "File Uploaded <br />";
echo 'File Successfully Uploaded to: ' . $target_Path;
echo '<br />';
echo 'File Name: ' . $_FILES['uploadimage']['name'];
echo'<br />';
echo 'File Type: ' . $_FILES['uploadimage']['type'];
echo'<br />';
echo 'File Size: ' . $_FILES['uploadimage']['size'];
}
?>
Show Image
showimage.php
<?php
$con=mysqli_connect("localhost","user_name","password","test"); //Change it if required
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM image " );
while($row = mysqli_fetch_array($result))
{
echo '<img src="' . $row['image'] . '" width="200" />';
echo'<br /><br />';
}
mysqli_close($con);
?>
I use the Following code to upload a single file .With This code I can Upload a single file to the database .I want to make multiple files uploaded by selecting multiple files in a single input type file.What Changes should i make in the code to make it upload multiple files?
<?PHP
INCLUDE ("DB_Config.php");
$id=$_POST['id'];
$fileTypes = array('txt','doc','docx','ppt','pptx','pdf');
$fileParts = pathinfo($_FILES['uploaded_file']['name']);
if(in_array($fileParts['extension'],$fileTypes))
{
$filename = $_FILES["uploaded_file"]["name"];
$location = "E:\\test_TrainingMaterial/";
$file_size = $_FILES["uploaded_file"]["size"];
$path = $location . basename( $_FILES['uploaded_file']['name']);
if(file_exists($path))
{
echo "File Already Exists.<br/>";
echo "Please Rename and Try Again";
}
else
{
if($file_size < 209715200)
{
$move = move_uploaded_file( $_FILES["uploaded_file"]["tmp_name"], $location . $_FILES['uploaded_file']['name']);
$result = $mysqli->multi_query("call sp_upload_file('".$id."','" . $filename . "','".$path."')");
if ($result)
{
do {
if ($temp_resource = $mysqli->use_result())
{
while ($row = $temp_resource->fetch_array(MYSQLI_ASSOC)) {
array_push($rows, $row);
}
$temp_resource->free_result();
}
} while ($mysqli->next_result());
}
if($move)
{
echo "Successfully Uploaded";
}
else
{
echo "File not Moved";
}
}
else
{
echo "File Size Exceeded";
}
}
}
else
{
echo " Invalid File Type";
}
?>
The Html That is used is
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file" id="uploaded_file" style="color:black" /><br/>
</form>
Basically you need to add to input name [] brackets and attribute "multiple"
<form id = "upload_form" method="post" enctype="multipart/form-data" >
<input type="file" name="uploaded_file[]" multiple="true" id="uploaded_file" style="color:black" /><br/>
</form>
Now all uploaded file will be available via
$_FILES['uploaded_file']['name'][0]
$_FILES['uploaded_file']['name'][1]
and so on
More info at
http://www.php.net/manual/en/features.file-upload.multiple.php
How can I save an image safely from a file input field using PHP & MySQL?
Here is the input file field.
<input type="file" name="pic" id="pic" size="25" />
This is a simple example, it should work.
Although you probably want to add checking for image types, file sizes, etc.
<?php
$image = $_POST['pic'];
//Stores the filename as it was on the client computer.
$imagename = $_FILES['pic']['name'];
//Stores the filetype e.g image/jpeg
$imagetype = $_FILES['pic']['type'];
//Stores any error codes from the upload.
$imageerror = $_FILES['pic']['error'];
//Stores the tempname as it is given by the host when uploaded.
$imagetemp = $_FILES['pic']['tmp_name'];
//The path you wish to upload the image to
$imagePath = "images/";
if(is_uploaded_file($imagetemp)) {
if(move_uploaded_file($imagetemp, $imagePath . $imagename)) {
echo "Sussecfully uploaded your image.";
}
else {
echo "Failed to move your image.";
}
}
else {
echo "Failed to upload your image.";
}
?>
http://php.net/file_upload covers just about everything you need to know.
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$tmpFile = $_FILES['pic']['tmp_name'];
$newFile = '/new_location/to/file/'.$_FILES['pic']['name'];
$result = move_uploaded_file($tmpFile, $newFile);
echo $_FILES['pic']['name'];
if ($result) {
echo ' was uploaded<br />';
} else {
echo ' failed to upload<br />';
}
}
?>
<form action="" enctype="multipart/form-data" method="POST>
<input type="file" name="pic" />
<input type="submit" value="Upload" />
</form>