Insert data into MYSQL database using PHP (PDO) and JQUERY.ajax()

We are going to learn how to insert data into MYSQL database using PDO (PHP Data Objects) and JQUERY.ajax(). Whole process will be shown step by step with all code presented.
Let’s start with connection to database. One of advantages of using PDO is that it enables uniform access across multiple databases. It allows seamless switching between different platforms and databases and it is done by changing the connection string. For this practice , we created database named ‘test_database’ and below is connection.php
<?php
define ("DSN","mysql:host=localhost;dbname=test_database");
define ("USERNAME","test");
define ("PASSWORD","test");
$options = array(PDO::ATTR_PERSISTENT =>true);
try{
$conn = new PDO (DSN,USERNAME,PASSWORD,$options);
$conn->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
echo "Connection succesfull";
} catch (PDOException $ex) {
// only during production
//echo "A database connection error occured ".$ex->getMessage();
echo "A database connection error occured ";
}
?>
Once connection is established we can proceed with creating table which we will be using for this exercise. Name of the table is ‘contacts’. Below is create_table.php
 <?php
include_once 'connection.php';

$table = "CREATE TABLE IF NOT EXISTS contacts (
 id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT,
 name VARCHAR (25) NOT NULL,
 surname VARCHAR (35) NOT NULL,
 email VARCHAR (50) NOT NULL,
 reg_date TIMESTAMP
 )";
try{ 
 $conn->query($table);
 echo "<br> Table 'contacts' created";
} catch (PDOException $ex) { 
 echo "<br> An error occured ".$ex->getMessage();
}
?>
Now, we will make form for entering data into database. For this exercise we will use Bootstrap (http://v4-alpha.getbootstrap.com/getting-started/introduction/#starter-template) to design index.php
 <!DOCTYPE html>
<html lang="en">
 <head>
 <meta charset="utf-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
 <title>Form : insert contact </title>
 <!-- Bootstrap -->
 <!-- Latest compiled and minified CSS -->
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
 <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
 <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
 <!--[if lt IE 9]>
 <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
 <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
 <![endif]--> 
 <link href="style.css" rel="stylesheet">
 </head>
 <body> 
 <div class="container"> 
 <h1>Insert form</h1>
 <br>
 <form id="insert_contact" action="insert.php" method="post">

 <div class="form-group">
 <label for="name">Name:</label>
 <input name="name" type="text" class="form-control" id="name" placeholder="">
 </div>
 <div class="form-group">
 <label for="surname">Surname:</label>
 <input name="surname" type="text" class="form-control" id="surname" placeholder="">
 </div>
 <div class="form-group">
 <label for="email">Email:</label>
 <input name="email" type="email" class="form-control" id="email" placeholder="">
 </div>
 <button type="submit" class="btn btn-default">Submit</button>
 </form>
 </div>
 <br>
 <br>
 <div id="alert_msg" class=" container alert alert-success"></div>

 <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
 <!-- Include all compiled plugins (below), or include individual files as needed -->
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
 <script src="insert.js"></script>
 </body>
</html>
When you run above index.php ‘div’ for alert message will be apear on open and we don’t want this to happen. To avoid this we use some css : style.css
 #alert_msg{
 text-align: center;
 border-radius: 2px;
 display: none;
 }
Main advantage od PDO is protection from SQL injection because user input does not reach database directly:insert.php
 <?php
include_once 'connection.php';

if (isset($_POST['name']) && isset($_POST['surname'])){ 
 $name = $_POST['name'];
 $surname = $_POST['surname'];
 $email = $_POST['email'];
 
try {
 $insertQuery = "INSERT INTO contacts (name, surname, email)
 VALUES (:name,:surname,:email)";
 $statement = $conn->prepare($insertQuery);
 $statement->execute(array(":name"=>$name, ":surname"=>$surname, ":email"=>$email));
 
if($statement){
 echo "Records inserted into database";
 }
}catch (PDOException $ex){ 
 echo "A problem occured :" .$ex->getMessage();
} 
} 
?>
We could submit form using only insert.php but I prefer to avoid to submit without refreshing the page so I suggest to use $.ajax . Below is insert.js
 $(document).ready(function () {
 $('#insert_contact').submit(function (event) {
 event.preventDefault();
 var form = $(this);
 var formData = form.serialize();
 $.ajax({
 url: 'insert.php',
 method: 'POST',
 data: formData,
 success: function (data) { 
 $('#alert_msg').css("display", "block").delay(3000).slideUp(300).html(data);
 $("#insert_contact")[0].reset();
 }
 });
 });
});

Post a Comment

7 Comments

  1. Orion One32 may be the best option if you’re looking for office space and retail space in Noida for property investment needs. In Sector 132 in Noida, there is a brand-new property that offers investment possibilities that fit your budget. The most coveted commercial property in Noida, Orion 132, offers real estate possibilities starting from Rs. 25 L  for those investors seeking exhilarating returns on their investments. Shops in Orion 132 Sector-132 provide significant foot traffic and optimum exposure. Additionally, this building includes top-notch grade A office space, providing substantial rental returns on investment from corporate clients. This is a high-end complex with modern amenities including reserved parking, power backup, visitor parking, landscaped gardens, courteous maintenance personnel, lifts, rainwater harvesting, 24×7 security, and water storage facilities. It is conveniently located at Sector 132, Noida Expressway. Customers of this venture are offered Assured Returns of 12%.

    ReplyDelete
  2. Best Skin Care Clinic in Delhi
    We have the Best Skin Care Clinic in Delhi. Our primary care physicians are moral, proficient, dependable, capable and reliable. Derma Point is the best skin care clinic in Delhi. Book an appointment now!



    Best Hair Transplant in Delhi
    klinik morphosis Hair Services is known for providing the Best Hair Transplant in Delhi, done by professional hair surgeons. We should our Hair Relocate experts in Delhi guide you through reestablishing your lost hair.



    FUE Hair Transplant Cost in Delhi
    Ultimately, apparatus came into the image by which the method got new progressions for FUE Hair Transplant in Delhi or Balding Treatment. These days, the total methodology is finished with cutting edge robotization in which punch gets appended to that specific apparatus. Utilising progressed Hair Rebuilding Methods, the speed of extraction hardware can be effectively constrained by the specialist, as each understanding requires an alternate speed for extraction relying on the skin surface, thickness, nature of unions, and others.


    Why Choose Non Surgical Hair Replacement System in Delhi?
    A Non-Surgical Hair Replacement in Delhi strategy is a logical technique for hair rebuilding in which your scalp is recovered into frames, without impeding your everyday schedules. You can proceed with a similar daily practice of hair washing, shampooing and brushing without the concern of the hair expansions tumbling off. The non-careful hair treatment has developed well known and numerous youngsters experiencing outrageous hair fall issues can finish the strategy at our centre at a reasonable cost. No other hair rebuilding cycle can give you the fabulous thickness to your hair like a non-careful hair substitution method.


    Best Hair Transplant Surgeons in Delhi
    Are you looking for a trusted best hair transplant clinic in Delhi ? We all know that India is the second-most populous country in the world and its capital is New Delhi. It has a vast history and a new-age of medical facilities. Many people around the world travel here for the Best Hair Transplant Clinic in Delhi . People came from many under-developed countries because of hair transplant costs.


    Best Hair Transplant Doctor in Delhi
    klinik morphosis Hair Transplants has been awarded as the Best Hair Transplant Doctor in Delhi NCR on numerous occasions. Based in Delhi, we have a team of world-renowned doctors who are widely known to carry out the best hair transplant doctor in Delhi.

    Klinik morphosis is the best hair transplant doctor in Delhi NCR,India with experienced doctors & surgeons.

    We have expertise in performing various procedures including FUE hair transplant, and aim to deliver best results to our patients. Get the best hair transplant doctor in Delhi.



    Best Hydrafacial in Delhi
    Are you time challenged but are still looking for a plump looking clear skin. We invite you to let your skin bathe in rich antioxidants and deeply hydrating hyaluronic acid, with our signature Hydrafacial in Delhi. This state of art treatment utilises novel technology to cleanse, exfoliate and hydrate. In Hydra Facial the serums and peptides are infused into the skin that leaves an instantly gratifying glow on your face.


    Hydrafacial Cost in Delhi
    Hydrafacial cost in Delhi is still not under everyone’s capacity, so we have designed a customised costing plan as per individuals’ need that makes up for the feasible cost management of patients.

    Our uniquely formulated water-based-formula facial and fusion technology together delivered by the Derma skin specialist is an ultimate solution to get rid of hyperpigmentation, signs of ageing, wrinkles, fine lines, earthy colored detects crow's feet, stopped up and developed pores, and touchy or skin break out inclined skin. The results are immediate with no downtime or discomfort.

    ReplyDelete