I have a table where each row has an image and some text. Currently, when I update the content without selecting an image, the database field for the image gets cleared out. However, I want to keep the old image if there's no image selected.
How can I accomplish this?
As a note, I know that mysql_* functions are deprecated.
<?php
include("db/db.php");
$select_db = "select * from aboutus WHERE id=1";
$run_news = mysql_query($select_db);
while ($row = mysql_fetch_array($run_news)) {
$id = $row['id'];
$image = $row['image'];
$content = $row['content'];
}
?>
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Update About Content</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form" method="post" action="aboutcontent.php?id=1" enctype="multipart/form-data">
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Reselect Image *(H=530px, W=800px)</label>
<input type="file" name="user_image" id="exampleInputFile">
</div>
<div class="form-group">
<label >Content</label><br>
<textarea name="content" class="tinymce" class="form-control" rows="15"><?php echo $content; ?></textarea>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" name="update" class="btn btn-primary">Update</button>
</div>
</form>
</div>
<?php
include("db/db.php");
// Code for UPDATE button
if (isset($_POST['update'])) {
$content = $_POST['content'];
$imgFile = $_FILES['user_image']['name'];
$tmp_dir = $_FILES['user_image']['tmp_name'];
$imgSize = $_FILES['user_image']['size'];
if ($imgFile) {
$upload_dir = 'images/about/'; // upload directory
$imgExt = strtolower(pathinfo($imgFile, PATHINFO_EXTENSION)); // get image extension
$valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions
$userpic = rand(1000, 1000000) . "." . $imgExt;
if (in_array($imgExt, $valid_extensions)) {
if ($imgSize < 5000000) {
unlink($upload_dir . $row['image']);
move_uploaded_file($tmp_dir, $upload_dir . $userpic);
}
else {
$errMSG = "Sorry, your file is too large it should be less then 5MB";
}
}
else {
$errMSG = "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
}
}
else {
// if no image selected the old image remain as it is.
$userpic = $row['image']; // old image from database
}
// if no error occured, continue ....
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
$query = mysql_query($sql);
if (!$query) {
die('Invalid query: ' . mysql_error());
}
else {
echo "<script>alert('Successfully Updated!!!'); window.location='index.php?aboutcontent'</script>";
}
}
?>
The problem can easily be solved by checking if a file was submitted or not:
if(!empty($userpic)){
// SQL update here
} else {
// No file submitted so don't update
}
The reason you were getting empty mysql fields is because you were updating the field with an empty variable.
Since I can't comment yet, when you submit without an image are you landing in the if or else statement (place a die('some content) in each part) to figure this out. If you are not making it to the else, try:
//initialize error message
$errMSG = '';
//this error means 'There is no error, the file uploaded with success'
if($_FILES['user_image']['error'] == 0){
//rest of logic to get the filename and move files stuff
}
else{
$userpic = $row['image'];
}
//you dont want to update database if there are errors
if(errMSG = ''{
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
OR just make two different database calls, one for when you have an image and one for when you dont
if($_FILES['user_image']['error'] == 0){
//rest of logic to get the filename and move files stuff
//if everything else is true (has filename and correct file size)
//you dont want to update database if there are errors
if(errMSG = ''{
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
$sql = "UPDATE aboutus SET image='$userpic', content='$content' WHERE id=1";
}
else{
$userpic = $row['image'];
$sql = "UPDATE aboutus SET content='$content' WHERE id=1";
}
http://php.net/manual/en/features.file-upload.errors.php
Related
m creating simple blog site, in creating new page, i have insert image gallery too. page and gallery both have two different table as i couldn’t figure out how to insert gallery into single table (means gallery section in pages table, so i created two tables)
What im trying to achieve in update pages is that check if image is insert or not in update page. if image is insert then display image else allow user to upload image in update page
table_name = english_version (table for page)
table for page
table_name = english_gallery (table for gallery)
table fro gallery
*Where image_id = id (id from english_version)
so when user creates new page and sumbit, it is send to update page:
header(“Location:./update.php?update=$lastenterid”);
die();
so, if user forget to insert image for gallery then i want to give option for image upload in update pages…
if(isset($_GET['update'])){
$update_id = intval($_GET['update']);
$update = $conn->query("SELECT * FROM english_version WHERE id = $update_id ");
while($rows = $update->fetch(PDO::FETCH_OBJ) ):
$id = $rows->id;
$title = $rows->title;
$content = $rows->content;
endwhile;
}
checking if image is insert or not
<form action="" method="post">
<!-- english-version -->
<input type="hidden" name="id" value="<?php echo $id;?>">
<div class="form-group">
<input type="text" name="title" class="form-control mt-3" value="<?php echo $title?>">
</div>
<div class="form-group">
<textarea class="form-control" name="content" id="" cols="30" rows="10"><?php echo $content;?></textarea>
</div>
<div class="form-group">
<?php
//getting data from english_gallery (table for gallery)
$gallery = $conn->query("SELECT * FROM english_gallery WHERE image_id = $update_id");
while($rows_gal = $gallery->fetch(PDO::FETCH_OBJ) ):
$id = $rows_gal->gallery_id;
$image_id = $rows_gal->image_id;
$image = $rows_gal->image;
//check if image_id == $update_id (where $update is id of (primary_key) english_version (table for page))
if($image_id == $update_id ){ ?>
<div class="image-gallery">
<img src="<?php echo $image;?>" alt="">
</div>
<?php
}else{
$targetDir = "image/";
$allowTypes = array('jpg','png','jpeg','gif');
$images_arr = array();
foreach($_FILES['images']['name'] as $key=>$val){
$image_name = $_FILES['images']['name'][$key];
$tmp_name = $_FILES['images']['tmp_name'][$key];
$size = $_FILES['images']['size'][$key];
$type = $_FILES['images']['type'][$key];
$error = $_FILES['images']['error'][$key];
// File upload path
$fileName = basename($_FILES['images']['name'][$key]);
$targetFilePath = $targetDir . $fileName;
// Check whether file type is valid
$fileType = pathinfo($targetFilePath,PATHINFO_EXTENSION);
if(in_array($fileType, $allowTypes)){
// Store images on the server
if(move_uploaded_file($_FILES['images']['tmp_name'][$key],$targetFilePath)){
$images_arr[] = $targetFilePath;
$insert = $conn->query("INSERT into english_gallery (image_id,image) VALUES ('$update_id','$targetFilePath')");
$galleryid = $conn->lastInsertId();
if($insert){
$count = $key + 1;
$statusMsg = " ".$count. " image file has been uploaded successfully.";
}else{
$statusMsg = "Failed to upload image";
}
}else{
$statusMsg = "Sorry, there was an error uploading your file.";
}
}else{
$statusMsg = 'Sorry, only JPG, JPEG, PNG, & GIF files are allowed to upload.';
}
}//multiple_image upload starts
?>
<!-- if image_id !== $update then display multi-image upload section -->
<div class="form-group">
<input type="file" name="images[]" multiple>
</div>
<?php
}
endwhile;
?>
</div>
<div class="form-group">
<input type="submit" value="Update" name="update" class="btn btn-primary">
</div>
<!-- english-version -->
if($image_id == $update_id ){
if there is image its displaying image but if there no image its not displaying input option for image upload
upload image
if think else conditions is not working because $image_id stores id of (primary_key) english_version (table for page)) it’s checking for the id which is never created…
so, how can i get the condition, where if user have insert image then image will displayed else user will get option for image uploading…
I have a very weird problem in my system. I already create a system to upload the image to the database and display it. The problem is, the image is successfully uploaded but, it will return the message "Failed to upload!". Then, the picture that had been uploaded does not display. Below is my code:
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
//File extension
$ext = strtolower(pathinfo($_FILES['uploadFile']['name'], PATHINFO_EXTENSION));
//Check extension
if(in_array($ext, $allowed_extensions)) {
//Convert image to base64
$encoded_image = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']));
$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$sql -> execute();
//$results = $sql -> fetchAll(PDO::FETCH_OBJ);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($sql->rowCount() > 1 ) {
echo "Status : Uploaded";
$last_insert_id = $conn-> lastInsertId();
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$sql = $conn->prepare($query);
$sql -> execute();
if($sql->rowCount($sql) == 1 ) {
//$row = mysqli_fetch_object($result);
while($row = $sql->fetch(PDO::FETCH_ASSOC)) {
echo "<br><br>";
echo '<img src="'.$row->encoded_image.'" width="250">';
}
}
}
}
?>
</div>
</body>
Can someone help me? Thanks!
you doing some thing wrong first you encoded the image when store in database so you must decode it again, and the src in tag get a url not image content just echo the content like this:
header('Content-type: image/jpeg');
echo base64_decode($row->encoded_image);
or
<img src="data:image/png;base64,'.$row->encoded_image.'" width="250">
but at all, store images in database is not a good option, your database become too heavy and can't respond fast and get too memory you can just store the image name in database and move the file form special place in your server the you can show like this.
echo '<img src="specialRoot/'.$row->image_name.'" width="250">';
Store images in folder..
I have created uploads folder in root, you can create folder at anywhere and write your path while fetching the image..
<body>
<div class="wrapperDiv">
<form action="" method="post" id="form" enctype="multipart/form-data">
Upload image :
<input type="file" name="uploadFile" value="" />
<input type="submit" name="submitBtn" value="Upload" />
</form>
<?php
$last_insert_id = null;
include('db2.php');
if(isset($_POST['submitBtn']) && !empty($_POST['submitBtn'])) {
if(isset($_FILES['uploadFile']['name']) && !empty($_FILES['uploadFile']['name'])) {
//Allowed file type
$allowed_extensions = array("jpg","jpeg","png","gif");
$name = $_FILES['uploadFile']['name'];
$target_dir = "uploads/"; //give path of your folder where images are stored.
$target_file = $target_dir . basename($_FILES["uploadFile"]["name"]);
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
//Check extension
if( in_array($imageFileType,$allowed_extensions) ){
//Convert image to base64
$image_base64 = base64_encode(file_get_contents($_FILES['uploadFile']['tmp_name']) );
$encoded_image = 'data:image/'.$imageFileType.';base64,'.$image_base64;
//$encoded_image = base64_encode($_FILES['uploadFile']['tmp_name']);
//$encoded_image = $encoded_image;
$query = "INSERT INTO tbl_images SET encoded_image = '".$encoded_image."'";
$sql = $conn->prepare($query);
$result = $sql -> execute();
move_uploaded_file($_FILES['uploadFile']['tmp_name'],$target_dir.$name);
echo "File name : " . $_FILES['uploadFile']['name'];
echo "<br>";
if($result == 1) {
echo "Status : Uploaded";
$last_insert_id = $conn->insert_id;
} else {
echo "Status : Failed to upload!";
}
} else {
echo "File not allowed";
}
}
if($last_insert_id) {
$query = "SELECT encoded_image FROM tbl_images WHERE id= ". $last_insert_id;
$result = $conn->query($query);
while($row = $result->fetch_assoc()){
echo '<img src="'.$row['encoded_image'].'" width="250">';
}
}
}
?>
</div>
</body>
Im currently in the process of creating a simple PHP website which can display a list of NBA teams and the respective players. One of the things I'm currently working on right now is adding the ability to upload images from the page itself instead of going to PHPMyAdmin.
Here's what the page looks like right now:
I'm trying to figure out how to add the team logo the same way I can add a new team name. As you can see in the bottom part there is an Add Team option which allows the user to add a new team and that team will be registered in the database.
I've tried to write some PHP code which enables the process of uploading images but have failed to do so.
team_list.php
<?php
error_reporting(0);
require_once('../Model/database.php');
// Get all categories
$query = 'SELECT * FROM categories
ORDER BY categoryID';
$statement = $db->prepare($query);
$statement->execute();
$teams = $statement->fetchAll();
$statement->closeCursor();
// Initialize message variable
$msg = "";
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image'];
// image file directory
$target = "images/".basename($image);
$sql = "INSERT INTO categories (img) VALUES ('$image')";
// execute query
mysqli_query($db, $sql);
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
}
$result = mysqli_query($db, "SELECT * FROM categories");
?>
<!DOCTYPE html>
<html>
<!-- the head section -->
<head>
<title>NBA</title>
<link rel="stylesheet" type="text/css" href="../css/index.css">
<link rel="shortcut icon" type="image/png" href="images/favicon.ico"/>
</head>
<!-- the body section -->
<body>
<main>
<h1 id="addCategoryh1">Teams</h1>
<table id="categoryListTable">
<tr>
<th>Name</th>
<th> </th>
</tr>
<?php foreach ($teams as $team) : ?>
<tr>
<td><?php echo $team['categoryName']; ?></td>
<td>
<form action="delete_team.php" method="post"
id="delete_product_form">
<input type="hidden" name="team_id"
value="<?php echo $team['categoryID']; ?>">
<input id="deleteCategoryList" type="submit" value="Delete">
</form>
</td>
</tr>
<?php endforeach; ?>
</table>
<br>
<?php
while ($row = mysqli_fetch_array($result)) {
echo "<div id='img_div'>";
echo "<img src='images/".$row['image']."' >";
echo "<p>".$row['image_text']."</p>";
echo "</div>";
}
?>
<h2 id="add_category_h2">Add Team</h2>
<form action="add_team.php" method="post"
id="add_category_form">
<label>Name:</label>
<input type="input" name="name">
<input id="add_category_button" type="submit" value="Add">
</form>
<form method="POST" action="team_list.php" enctype="multipart/form-data">
<input type="hidden" name="size" value="1000000">
<div>
<input type="file" name="image">
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
</form>
<br>
<p>View Team List</p>
</main>
<footer id="categoryListFooter">
<p>© <?php echo date("Y"); ?> NBA</p>
</footer>
</body>
</html>
And this is the add_team.php file, which gets the data from database
<?php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
}
?>
This is how the standing.php page looks like
updated add_team.php
// Get the team data
$name = filter_input(INPUT_POST, 'name');
// Validate inputs
if ($name == null) {
$error = "Invalid team data. Check all fields and try again.";
include('../Error/error.php');
} else {
require_once('../Model/database.php');
// Add the product to the database
$query = 'INSERT INTO categories (categoryName)
VALUES (:team_name)';
$query = "INSERT INTO categories (image) VALUES ('$fileName', '$content')";
$statement = $db->prepare($query);
$statement->bindValue(':team_name', $name);
$statement->execute();
$statement->closeCursor();
// Display the team List page
include('team_list.php');
// This is the directory where images will be saved
$target = "../images/";
$target = $target . basename( $_FILES['image']['name']);
// This gets all the other information from the form
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
mysql_connect("renwid", "password") or die(mysql_error()) ;
mysql_select_db("nba") or die(mysql_error()) ;
//Writes the information to the database
mysql_query("INSERT INTO categories (img, team_name)
VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
You have to first upload successfully to the folder then you can add record in to your database
<?php
if(isset($_POST['submit'])) {
// This is the directory where images will be saved
$target = "images/";
$target = $target . basename( $_FILES['image']['name']);
// This gets all the other information from the form
$filename = basename( $_FILES['image']['name']);
$team_name = $_POST['team_name'];
// Write the file name to the server
if(move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['image']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
// mysql_connect("localhost", "root", "") or die(mysql_error()) ;
// mysql_select_db("your_db") or die(mysql_error()) ;
//Writes the information to the database
// mysql_query("INSERT INTO picture (image, team_name)
// VALUES ('$filename', '$team_name')") ;
} else {
//Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
}
?>
Your HTML should be
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="image" id="image">
<input type="text" name="team_name" id="team_name">
<input type="submit" value="Submit" name="submit">
</form>
Refer https://github.com/aslamanver/nbaTest
You should create a uniqid when uploading the image, this way depending on how many people will upload images, if one were to upload the same image as another, it wouldn't be overwritten in the database
You can do this by using the explode and end function in PHP, also look into prepared statements when using SQL statements, this is to protect your DB against SQL injections, here's a good link:
https://www.w3schools.com/php/php_mysql_prepared_statements.asp
The $_FILES has a few attributes including $_FILES["name"]["error"] which checks for errors, ideally you would make an if statement in which you specify the error condition for the file to uploaded to your DB. Also remember that you must first specify the directory before inserting it into your DB and if the file containing the code is in another folder, you use ../ to go back a directory.
When you display the image on your site you use this:
<img src="directory/<?php echo $row["row"]; ?>">
I have been working on a multi-image upload function that I can't seem to make work. It currently will only work if I have a single image uploaded. I can't figure out what is going wrong with this script.
This is the function to upload images:
if(isset($_POST["btnSubmit"])){
$errors = array();
$extension = array("jpeg","jpg","png","gif");
$bytes = 1000000;
$allowedKB = 10485760000;
$totalBytes = $allowedKB * $bytes;
$imgDir = "assets/users/".$userLoggedIn."/images/";
if(isset($_FILES["files"])==false)
{
echo "<b>Please, Select the files to upload!!!</b>";
return;
}
foreach($_FILES["files"]["tmp_name"] as $key=>$tmp_name)
{
$uploadThisFile = true;
$file_name=$_FILES["files"]["name"][$key];
$file_tmp=$_FILES["files"]["tmp_name"][$key];
$ext=pathinfo($file_name,PATHINFO_EXTENSION);
if(!in_array(strtolower($ext),$extension))
{
array_push($errors, "File type is invalid. Name:- ".$file_name);
$uploadThisFile = false;
}
if($_FILES["files"]["size"][$key] > $totalBytes){
array_push($errors, "File size is too big. Name:- ".$file_name);
$uploadThisFile = false;
}
if($uploadThisFile){
$filename = basename($file_name,$ext);
$newFileName = uniqid().$filename.$ext;
move_uploaded_file($_FILES["files"]["tmp_name"][$key],$imgDir.$newFileName);
// current date and time
$date_added = date("Y-m-d H:i:s");
$imagePath = $imgDir.$newFileName;
$query = "INSERT INTO images(date_added, added_by, image, deleted) VALUES('$date_added', '$userLoggedIn','$imagePath', 'no')";
mysqli_query($con, $query);
}
}
header("Location: edit-images.php");
$count = count($errors);
if($count != 0){
foreach($errors as $error){
echo $error."<br/>";
}
}
}
?>
I thought the issue might be with size but I cut the condition to prevent it from uploading with no luck. I feel like I might be missing something in the foreach but I am completely stuck. I appreciate your help!
Here is the form I am using to upload:
<form method="post" enctype="multipart/form-data" name="formUploadFile" id="uploadForm" action="edit-images.php">
<div class="form-group">
<label for="exampleInputFile">Select file to upload:</label>
<input type="file" id="exampleInputFile" name="files[]" multiple="multiple">
<p class="help-block"><span class="label label-info">Note:</span> Please, Select the only images (.jpg, .jpeg, .png, .gif)</p>
</div>
<button type="submit" class="btn btn-primary" name="btnSubmit" >Start Upload</button>
</form>
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".