Uploading Data & Image to store in MySQL table

How to display images from MySQL database records
How to delete images and record from MySQL database records
We will learn how to upload image along with other form data by using JQuery and Ajax.
PHP file upload script is with all checks, you can download the full script at end of this tutorial.
We will show a form to users to add product name , price and then select an image of the product to upload.
Name

Price

Upload file

To display the above form we will be using this code.
<div class='row'>
  <div class='col-md-3 col-md-offset-2'>Name</div>
  <div class='col-md-3'><input type='text' class='form-control' id='userid' name=p_name placeholder='Product Name'></div>
</div>
<br>
<div class='row'>
  <div class='col-md-3 col-md-offset-2'>Price</div>
  <div class='col-md-3'><input type='text' class='form-control' id='userid' name=price placeholder='Price'></div>
</div>
<br>
<div class='row'>
  <div class='col-md-3 col-md-offset-2'>Upload file</div>
  <div class='col-md-4'><input type=file name='file_up'></div>
</div>

<br>
<div class='row'>
  <div class='col-md-3 col-md-offset-2'></div>
  <div class='col-md-4'><button>Submit</button></FORM></div>
</div>
The submit button will trigger the JQuery code to post the data to backend PHP script to check , upload image and insert record into our database.
$("form#data").submit(function(e) {
 e.preventDefault();    
 var formData = new FormData(this);
 $.ajax({
  url: 'add-recordck.php',
  type: 'POST',
  data: formData,
  dataType: 'json',
  success: function (return_data) {
   if(return_data.validation_status=='T'){
	$('form#data').trigger("reset");
   }
  $("#msg_display").html(return_data.msg);     
  $("#msg_display").show();
 setTimeout(function() { $("#msg_display").fadeOut('slow'); }, 4000);
     },
   cache: false,
   contentType: false,
   processData: false
  });
});
You can see on successful upload and insertion of record into table, we will display message to user. On failure also we will display reason for the user to correct it.
 success: function (return_data) {
 if(return_data.validation_status=='T'){
 $('form#data').trigger("reset");
 }
 $("#msg_display").html(return_data.msg);     
 $("#msg_display").show();
 setTimeout(function() { $("#msg_display").fadeOut('slow'); }, 4000);
 }
Following checks are performed at backend script and matching reply is posted to user .

Product name should have Alphabet , number and space. No special chars are allowed.
Price should be float ( 22.34 )
Image must be jpg or gif type, file size should be less than 250KB.

Backend PHP Script add-recordck.php

Receiving the data and setting the flags
$p_name=$_POST['p_name'];
$price=$_POST['price'];
$elements=array("msg"=>"","records_affected"=>"","validation_status"=>"T");
Check the price format
if(!filter_var($price,FILTER_VALIDATE_FLOAT)){
$elements['msg'].=" Enter Price details <br>";	
$elements['validation_status']="F";
}
Check Product name
if(!ctype_alpha(str_replace(' ', '', $p_name)) === true){
$elements['msg'].=" Enter Product Name without Special Chars <br>";
$elements['validation_status']="F";
}
Check file type ( only Gif and Jpg are allowed )
if (!($_FILES[file_up][type] =="image/jpeg" OR $_FILES[file_up][type] =="image/gif"))
{$elements['msg'].="Your uploaded file must be of JPG or GIF. ";
$elements['msg'].="Other file types are not allowed<BR>";
$elements['validation_status']="F";	// Set the flag to F
}
Check file size ( upto 250 KB )
if ($_FILES[file_up][size]>250000){
$elements['msg'].="Your uploaded file size is more than 250KB ";
$elements['msg'].=" so reduce the file size and then upload.<BR>";
$elements['validation_status']="F";	 // Set the flag to F
}
If all above validations are cleared then we will go for uploading the file.
$file_name=$_FILES[file_up][name];// Name of the file upload
if($elements['validation_status']=="T"){
// the path with the file name where the file will be stored
$add="images/$file_name"; 
if(move_uploaded_file ($_FILES[file_up][tmp_name], $add)){
/// Other code to store record in database 	
}
}
After uploading we will insert one record to MySQL database table with Product name, price and file name.
$query="INSERT INTO plus2_db_images (p_name,price,img) values(?,'$price',?)";
$stmt=$connection->prepare($query);
if($stmt){ 
$stmt->bind_param("ss", $p_name,$file_name);
if($stmt->execute()){
$elements['msg'].= "Records added : ".$connection->affected_rows;
$elements['msg'].= "<br>Product ID : ".$connection->insert_id;
}else{
$elements['validation_status']="F";		
$elements['msg'].="Database error : ". $connection->error;
}
}else{
$elements['validation_status']="F";		
$elements['msg'].="Database error : ". $connection->error;
}
Each stage we will be setting the validation status to T or F and adding a message about the success or failure of the process for the user .
Finally we will use JSON to post back the message to user.
echo json_encode($elements);

Downloading Zip file

Download the zip file and use this instructions to run the file.
How to Install and test
  • Download the zip file at the end of this page. plus2_db_images_v2.zip
  • include\config.php : Add your database login details ( MySQLi connection ).
  • include\config-pdo.php : Add your database login details ( PDO connection ).
  • index.php : PHP script to show images from database using MySQLi.
  • index-pdo.php : PHP script to show images from database using PDO.
  • add-record.php : Add image with details to database .
  • delete-record.php : Delete image & database record .
  • sql_dump.txt : MySQL dump to create database table .
(only Display Image )


( With Add and Delete Image )



Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com




    Post your comments , suggestion , error , requirements etc here .




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer