AngularJS insert using php MYSQL



  • The Insert statement is used to insert the data to the MySQL database.
  • In AngularJS we should post the form data in JSON format to insert into the PHP file.
  • The PHP server side code used to get the posted data from AngularJS and decode the JSON format.
  • The MySQL connection and query execution also done in PHP code.

Syntax for MySQL Insert Statement with PHP and MySQL:

$conn = mysql_connect('myServer', ' myUser ', ' myPassword ');
mysql_select_db(' myDb ', $conn);
$result=mysql_query("insert into tbl_name (col1, col2, col3) values ( val1, val2 , val3)");

Syntax for MySQL Insert Statement with PHP and MySQLi:

$conn = mysqli_connect('myServer', 'myUser', 'myPassword', 'myDb');
$result=mysqli_query($conn, "insert into tbl_name (col1, col2, col3) values 
( val1, val2 , val3)");
                     

Syntax for MySQL Insert Statement with PHP and PDO:

$conn = new PDO ("mysql:host=myServer;dbname=myDb", "myUser", "myPassword");
$result=$conn->query("insert into tbl_name (col1, col2, col3) values ( val1, val2 , val3)");

Sample code for MySQL Insert with PHP in AngularJS:

  • Let’s create a sample code for MySQL insert with PHP by PDO method.
 Tryit<!DOCTYPE html>
<html>
    <head>
        <title>Wikitechy AngularJS Tutorials</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/
        angular.min.js"> </script>
    </head>
    <body ng-app="insertApp" ng-controller=" insertCtrl">
        <h1>MYSQL Insert with PHP in AngularJS</h1>
        <form name="userForm" ng-submit=" submitForm()">
           <p>Enter Name :<input type="text" required ng-model="user.name"></p>
           <p>Enter Mobile :<input type="text" required ng-model="user.mobile"></p>
           <p>Enter Email :<input type="email" required ng-model="user.email"></p>
           <button type="submit">Insert</button><br>
        </form>
        <table border="1">
                <tr>
                    <th>ID</th>
                    <th>Name</th>
                    <th>Mobile</th>
                    <th>Email</th>
                </tr>
                <tr ng-repeat="x in content" >
                    <td>{{x.id}}</td>
                    <td>{{x.name}}</td>
                    <td>{{x.mobile}}</td>
                    <td>{{x. email}}</td>
                </tr>
            </table>
            <h3>Please Use Ctrl+F5 for Refresh</h3>
    </body>
    <script>
        var app = angular.module("insertApp", []);
        app.controller("insertCtrl", function($scope, $http) {
            $http.get("select.php").then(function(response) { 
                $scope.content = response.data.details;       
            });
            $scope.user = {};
            $scope.submitForm = function() {
               $http({ method  : 'POST',
               url :'insert.php',
               data : $scope.user,
               headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
               }) .success(function(data) {
                   $scope.content = data;
               });
            };
        });
    </script>
</html>

POST Data to PHP File in JSON format:

  • Set of data has been posted through AngularJS to PHP and retrieve the result from PHP file.

    $scope.submitForm = function() {
        $http({ method  : 'POST',
        url :'insert.php',
        data : $scope.user,
        headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
        }) .success(function(data) {
            $scope.content = data;
    });

Code Explanation for MySQL Insert with PHP in AngularJS:

Code Explanation for AngularJS insert Using PHP Mysql

  1. The submitForm() function is used to call the function on form submit.
  2. The textbox is used to get the name from the user.
  3. The textbox is used to get the Mobile Number from the user.
  4. The textbox is used to get the email from the user.
  5. To bind the content to <td> by ng-repeat directive.
  6. The “insertCtrl” used to create the controller for the Application with arguments $scope object and $http service.
  7. The $http is a service and it is used to call the get method, this http get request will get the content from the “select.php” as response.
  8. The response.data.details is used to get the response data.
  9. The submitForm function is used to POST the submitted data $scope.user to the “insert.php“.
  10. The $scope.content=data is used to get the updated results as response data.

Sample code for insert.php:

<?php
    error_reporting(0);
    $conn = new PDO("mysql:host=myServer;dbname=myDb", "myUser", "myPassword");   
    $_POST = json_decode(file_get_contents('php://input'), true);
    if(!empty($_POST['name'])&& !empty($_POST['mobile']))
    {
       $ins_query=$conn->prepare("insert into tbl_name (name, mobile, email)
        values( :name,:mobile , :email)");
       $ins_query->bindParam(':name', $_POST['name']);
       $ins_query->bindParam(':mobile', $_POST['mobile']);
       $ins_query->bindParam(':email', $_POST['email']);
       $chk_ins=$ins_query->execute();
    }
    $result = $conn->prepare("select * from tbl_name order by id ");
    $sel_query->execute();
    echo json_encode($sel_query->fetchAll());
?> 

Code Explanation for insert.php:

Code Explanation for AngularJS insert Using PHP Mysql

  1. The $conn connection string used to connect the MySQL database by PHP.
  2. The json_decode function is used to decode the JSON formatted POST data.
  3. To check the posted data is empty or not.
  4. To prepare the insert query for insert into the Mysql Database table.
  5. To bind the set of submitted data to the insert query and execute the insert query.
  6. To select the updated data in the table.
  7. To fetch all data from the result set and encode the data in JSON format.

Sample Output for MySQL Insert with PHP in AngularJS:

Sample Output for AngularJS insert using PHP Mysql

  1. The output shows the form to get input from user.
  2. The table data retrieved from MySQL database.
  3. Sample Output for AngularJS insert using PHP Mysql
  4. The details are filled in the form.
  5. Sample Output for AngularJS insert using PHP Mysql
  6. User fill-up the form after that click the Insert button.
  7. When user click the Insert button the data will be inserted to the MySQL database and retrieved from the MySQL table.


Related Searches to AngularJS insert using PHP Mysql