Monday, 9 October 2017

AngularJS Tutorial with PHP - Insert Data into Mysql Database


Source Code

Database


 --  
 -- Table structure for table `tbl_user`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_user` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `first_name` varchar(200) NOT NULL,  
  `last_name` varchar(200) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=22 ;  
 --  
 -- Dumping data for table `tbl_user`  
 --  
 INSERT INTO `tbl_user` (`id`, `first_name`, `last_name`) VALUES  
 (18, 'Mark', 'John');  


index.php


 <!DOCTYPE html>  
 <!-- index.php !-->  
 <html>  
      <head>  
           <title>Webslesson Tutorial | AngularJS Tutorial with PHP - Insert Data into Mysql Database</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:500px;">  
                <h3 align="center">AngularJS Tutorial with PHP - Insert Data into Mysql Database</h3>  
                <div ng-app="myapp" ng-controller="usercontroller">  
                     <label>First Name</label>  
                     <input type="text" name="first_name" ng-model="firstname" class="form-control" />  
                     <br />  
                     <label>Last Name</label>  
                     <input type="text" name="last_name" ng-model="lastname" class="form-control" />  
                     <br />  
                     <input type="submit" name="btnInsert" class="btn btn-info" ng-click="insertData()" value="ADD"/>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 var app = angular.module("myapp",[]);  
 app.controller("usercontroller", function($scope, $http){  
      $scope.insertData = function(){  
           $http.post(  
                "insert.php",  
                {'firstname':$scope.firstname, 'lastname':$scope.lastname}  
           ).success(function(data){  
                alert(data);  
                $scope.firstname = null;  
                $scope.lastname = null;  
           });  
      }  
 });  
 </script>  

insert.php


 <?php  
 //insert.php  
 $connect = mysqli_connect("localhost", "root", "", "testing");  
 $data = json_decode(file_get_contents("php://input"));  
 if(count($data) > 0)  
 {  
      $first_name = mysqli_real_escape_string($connect, $data->firstname);       
      $last_name = mysqli_real_escape_string($connect, $data->lastname);  
      $query = "INSERT INTO tbl_user(first_name, last_name) VALUES ('$first_name', '$last_name')";  
      if(mysqli_query($connect, $query))  
      {  
           echo "Data Inserted...";  
      }  
      else  
      {  
           echo 'Error';  
      }  
 }  
 ?>  

    AngularJS Tutorial with PHP - Fetch / Select Data from Mysql Database


    Source Code

    Database


     --  
     -- Table structure for table `tbl_user`  
     --  
     CREATE TABLE IF NOT EXISTS `tbl_user` (  
      `id` int(11) NOT NULL AUTO_INCREMENT,  
      `first_name` varchar(200) NOT NULL,  
      `last_name` varchar(200) NOT NULL,  
      PRIMARY KEY (`id`)  
     ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=32 ;  
     --  
     -- Dumping data for table `tbl_user`  
     --  
     INSERT INTO `tbl_user` (`id`, `first_name`, `last_name`) VALUES  
     (31, 'Tom', 'Cruze'),  
     (30, 'Bill', 'Gates'),  
     (29, 'John', 'Smith'),  
     (28, 'Big', 'Show'),  
     (27, 'Smith', 'Johnson'),  
     (26, 'The', 'Rock'),  
     (25, 'Peter', 'Parker'),  
     (18, 'Mark', 'John');  
    

    index.php


     <!DOCTYPE html>  
     <!-- index.php !-->  
     <html>  
          <head>  
               <title>Webslesson Tutorial | AngularJS Tutorial with PHP - Fetch / Select Data from Mysql Database</title>  
               <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
               <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
          </head>  
          <body>  
               <br /><br />  
               <div class="container" style="width:500px;">  
                    <h3 align="center">AngularJS Tutorial with PHP - Fetch / Select Data from Mysql Database</h3>  
                    <div ng-app="myapp" ng-controller="usercontroller" ng-init="displayData()">  
                         <label>First Name</label>  
                         <input type="text" name="first_name" ng-model="firstname" class="form-control" />  
                         <br />  
                         <label>Last Name</label>  
                         <input type="text" name="last_name" ng-model="lastname" class="form-control" />  
                         <br />  
                         <input type="submit" name="btnInsert" class="btn btn-info" ng-click="insertData()" value="ADD"/>  
                         <br /><br />  
                         <table class="table table-bordered">  
                              <tr>  
                                   <th>First Name</th>  
                                   <th>Last Name</th>  
                              </tr>  
                              <tr ng-repeat="x in names">  
                                   <td>{{x.first_name}}</td>  
                                   <td>{{x.last_name}}</td>  
                              </tr>  
                         </table>  
                    </div>  
               </div>  
          </body>  
     </html>  
     <script>  
     var app = angular.module("myapp",[]);  
     app.controller("usercontroller", function($scope, $http){  
          $scope.insertData = function(){  
               $http.post(  
                    "insert.php",  
                    {'firstname':$scope.firstname, 'lastname':$scope.lastname}  
               ).success(function(data){  
                    alert(data);  
                    $scope.firstname = null;  
                    $scope.lastname = null;  
                    $scope.displayData();  
               });  
          }  
          $scope.displayData = function(){  
               $http.get("select.php")  
               .success(function(data){  
                    $scope.names = data;  
               });  
          }  
     });  
     </script>  
    

    select.php


     <?php  
     //select.php  
     $connect = mysqli_connect("localhost", "root", "", "testing");  
     $output = array();  
     $query = "SELECT * FROM tbl_user";  
     $result = mysqli_query($connect, $query);  
     if(mysqli_num_rows($result) > 0)  
     {  
          while($row = mysqli_fetch_array($result))  
          {  
               $output[] = $row;  
          }  
          echo json_encode($output);  
     }  
     ?>  
    

      AngularJS Tutorial with PHP - Delete Mysql Table Data

      Source Code


       <!DOCTYPE html>  
       <!-- index.php !-->  
       <html>  
            <head>  
                 <title>Webslesson Tutorial | AngularJS Tutorial with PHP - Delete Mysql Table Data</title>  
                 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
                 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
            </head>  
            <body>  
                 <br /><br />  
                 <div class="container" style="width:500px;">  
                      <h3 align="center">AngularJS Tutorial with PHP - Delete Mysql Table Data</h3>  
                      <div ng-app="myapp" ng-controller="usercontroller" ng-init="displayData()">  
                           <label>First Name</label>  
                           <input type="text" name="first_name" ng-model="firstname" class="form-control" />  
                           <br />  
                           <label>Last Name</label>  
                           <input type="text" name="last_name" ng-model="lastname" class="form-control" />  
                           <br />  
                           <input type="hidden" ng-model="id" />  
                           <input type="submit" name="btnInsert" class="btn btn-info" ng-click="insertData()" value="{{btnName}}"/>  
                           <br /><br />  
                           <table class="table table-bordered">  
                                <tr>  
                                     <th>First Name</th>  
                                     <th>Last Name</th>  
                                     <th>Update</th>  
                                     <th>Delete</th>  
                                </tr>  
                                <tr ng-repeat="x in names">  
                                     <td>{{x.first_name}}</td>  
                                     <td>{{x.last_name}}</td>  
                                     <td><button ng-click="updateData(x.id, x.first_name, x.last_name)" class="btn btn-info btn-xs">Update</button></td>  
                                     <td><button ng-click="deleteData(x.id )"class="btn btn-danger btn-xs">Delete</button></td>  
                                </tr>  
                           </table>  
                      </div>  
                 </div>  
            </body>  
       </html>  
       <script>  
       var app = angular.module("myapp",[]);  
       app.controller("usercontroller", function($scope, $http){  
            $scope.btnName = "ADD";  
            $scope.insertData = function(){  
                 if($scope.firstname == null)  
                 {  
                      alert("First Name is required");  
                 }  
                 else if($scope.lastname == null)  
                 {  
                      alert("Last Name is required");  
                 }  
                 else  
                 {  
                      $http.post(  
                           "insert.php",  
                           {'firstname':$scope.firstname, 'lastname':$scope.lastname, 'btnName':$scope.btnName, 'id':$scope.id}  
                      ).success(function(data){  
                           alert(data);  
                           $scope.firstname = null;  
                           $scope.lastname = null;  
                           $scope.btnName = "ADD";  
                           $scope.displayData();  
                      });  
                 }  
            }  
            $scope.displayData = function(){  
                 $http.get("select.php")  
                 .success(function(data){  
                      $scope.names = data;  
                 });  
            }  
            $scope.updateData = function(id, first_name, last_name){  
                 $scope.id = id;  
                 $scope.firstname = first_name;  
                 $scope.lastname = last_name;  
                 $scope.btnName = "Update";  
            }  
            $scope.deleteData = function(id){  
                 if(confirm("Are you sure you want to delete this data?"))  
                 {  
                      $http.post("delete.php", {'id':id})  
                      .success(function(data){  
                           alert(data);  
                           $scope.displayData();  
                      });  
                 }  
                 else  
                 {  
                      return false;  
                 }  
            }  
       });  
       </script>  
      

      delete.php


       <?php  
       //delete.php  
       $connect = mysqli_connect("localhost", "root", "", "testing");  
       $data = json_decode(file_get_contents("php://input"));  
       if(count($data) > 0)  
       {  
            $id = $data->id;  
            $query = "DELETE FROM tbl_user WHERE id='$id'";  
            if(mysqli_query($connect, $query))  
            {  
                 echo 'Data Deleted';  
            }  
            else  
            {  
                 echo 'Error';  
            }  
       }  
       ?>  
      

        AngularJS Tutorial with PHP - Update / Edit Mysql Table Data

        Hello friends in this blog we are going to learn how to update or Edit Mysql table data by using Angular Javascript with PHP script. In previous post we have learn about how to fetch or select data from Mysql database table and display that data on web page without page refresh. But We have move one step ahead like how to edit inserted data by using PHP with Angular Javascript framework. If you have work on any project with Angular Javascipt Framework with PHP and if you work with form data, so at that time you have to required to update data which you have insert into the system, so how to update form data by using Angular Javascript with PHP programming without page refresh event. With help of Angular Javascript directive we can update Mysql table data by using PHP code from back end side operation and we can update data on front end side by using Angular Javascript function without page refresh event. So this is my tutorial on how to update mysql data by using Angular Javascript with php language. In this blog we have make update data function with three argument, when user click on update button textbox are filled with data and we have write php code for update data, we have also discuss how to change button name as per requirement and last and very important things like required field validation also we have discuss in this video which attached with this post.


        Source Code

        index.php


         <!DOCTYPE html>  
         <!-- index.php !-->  
         <html>  
              <head>  
                   <title>Webslesson Tutorial | AngularJS Tutorial with PHP - Update / Edit Mysql Table Data</title>  
                   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
                   <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>  
              </head>  
              <body>  
                   <br /><br />  
                   <div class="container" style="width:500px;">  
                        <h3 align="center">AngularJS Tutorial with PHP - Update / Edit Mysql Table Data</h3>  
                        <div ng-app="myapp" ng-controller="usercontroller" ng-init="displayData()">  
                             <label>First Name</label>  
                             <input type="text" name="first_name" ng-model="firstname" class="form-control" />  
                             <br />  
                             <label>Last Name</label>  
                             <input type="text" name="last_name" ng-model="lastname" class="form-control" />  
                             <br />  
                             <input type="hidden" ng-model="id" />  
                             <input type="submit" name="btnInsert" class="btn btn-info" ng-click="insertData()" value="{{btnName}}"/>  
                             <br /><br />  
                             <table class="table table-bordered">  
                                  <tr>  
                                       <th>First Name</th>  
                                       <th>Last Name</th>  
                                       <th>Update</th>  
                                  </tr>  
                                  <tr ng-repeat="x in names">  
                                       <td>{{x.first_name}}</td>  
                                       <td>{{x.last_name}}</td>  
                                       <td><button ng-click="updateData(x.id, x.first_name, x.last_name)" class="btn btn-info btn-xs">Update</button></td>  
                                  </tr>  
                             </table>  
                        </div>  
                   </div>  
              </body>  
         </html>  
         <script>  
         var app = angular.module("myapp",[]);  
         app.controller("usercontroller", function($scope, $http){  
              $scope.btnName = "ADD";  
              $scope.insertData = function(){  
                   if($scope.firstname == null)  
                   {  
                        alert("First Name is required");  
                   }  
                   else if($scope.lastname == null)  
                   {  
                        alert("Last Name is required");  
                   }  
                   else  
                   {  
                        $http.post(  
                             "insert.php",  
                             {'firstname':$scope.firstname, 'lastname':$scope.lastname, 'btnName':$scope.btnName, 'id':$scope.id}  
                        ).success(function(data){  
                             alert(data);  
                             $scope.firstname = null;  
                             $scope.lastname = null;  
                             $scope.btnName = "ADD";  
                             $scope.displayData();  
                        });  
                   }  
              }  
              $scope.displayData = function(){  
                   $http.get("select.php")  
                   .success(function(data){  
                        $scope.names = data;  
                   });  
              }  
              $scope.updateData = function(id, first_name, last_name){  
                   $scope.id = id;  
                   $scope.firstname = first_name;  
                   $scope.lastname = last_name;  
                   $scope.btnName = "Update";  
              }  
         });  
         </script>  
        



        insert.php


         <?php  
         //insert.php  
         $connect = mysqli_connect("localhost", "root", "", "testing");  
         $data = json_decode(file_get_contents("php://input"));  
         if(count($data) > 0)  
         {  
              $first_name = mysqli_real_escape_string($connect, $data->firstname);       
              $last_name = mysqli_real_escape_string($connect, $data->lastname);  
              $btn_name = $data->btnName;  
              if($btn_name == "ADD")  
              {  
                   $query = "INSERT INTO tbl_user(first_name, last_name) VALUES ('$first_name', '$last_name')";  
                   if(mysqli_query($connect, $query))  
                   {  
                        echo "Data Inserted...";  
                   }  
                   else  
                   {  
                        echo 'Error';  
                   }  
              }  
              if($btn_name == 'Update')  
              {  
                   $id = $data->id;  
                   $query = "UPDATE tbl_user SET first_name = '$first_name', last_name = '$last_name' WHERE id = '$id'";  
                   if(mysqli_query($connect, $query))  
                   {  
                        echo 'Data Updated...';  
                   }  
                   else  
                   {  
                        echo 'Error';  
                   }  
              }  
         }  
         ?>  

        Friday, 6 October 2017

        How to get value from MySQL with Node.js

        Please Share this to your social media if this is useful for you

        This time I'd like to share a basic and simple example of CRUD Operation in Node.js and MySQL. Its a lil bit hard to find tutorial Node.js n MySQL as poeple tend to use Mongoose instead of MySQL.

        LIVE DEMO HERE

        "note that there's no input validation on the Demo, just a crud example"
        ** UPDATE **
        I've created RESTFul Crud example with newest version of express and other dependencies here

        Before we start, Please mind the environment of this Application.
        • I'm using Ubuntu
        • NPM, Express 
        • MySQL for Node
        I haven't tested it yet on Windows. but i bet this will work too.

        Installing all those things above

        After your installation's complete, lets start creating your project folder:
        ubuntu@AcerXtimeline:~$ express hello_world
        once your hello_world folder is ready, Install MySQL. Go inside hello_world
        ubuntu@AcerXtimeline:~/hello_world$ npm install mysql
        
        We need a connection manager in Express. install it 
        ubuntu@AcerXtimeline:~/hello_world$ npm install express-myconnection

        Now take a look at this Folder structure

        Screenshot from 2014-05-02 17:03:04


        See your folder structure, compare it to the picture above. make new folder/files that you dont have yet in folder just like on the pic.

        Are we ready yet ? 

        1. Create a MySQL Database : nodejs  and create a table customer (id,name,address,email,phone).  or you can import the SQL in source code (see the end of this tuts)

        2. Open app.js . by default some codes are already given for you. we'll just need to add a lil more codes.

        /**
         * Module dependencies.
         */
        var express = require('express');
        var routes = require('./routes');
        var http = require('http');
        var path = require('path');
        //load customers route
        var customers = require('./routes/customers'); 
        var app = express();
        var connection  = require('express-myconnection'); 
        var mysql = require('mysql');
        // all environments
        app.set('port', process.env.PORT || 4300);
        app.set('views', path.join(__dirname, 'views'));
        app.set('view engine', 'ejs');
        //app.use(express.favicon());
        app.use(express.logger('dev'));
        app.use(express.json());
        app.use(express.urlencoded());
        app.use(express.methodOverride());
        app.use(express.static(path.join(__dirname, 'public')));
        // development only
        if ('development' == app.get('env')) {
          app.use(express.errorHandler());
        }
        /*------------------------------------------
            connection peer, register as middleware
            type koneksi : single,pool and request 
        -------------------------------------------*/
        app.use(
            
            connection(mysql,{
                
                host: 'localhost',
                user: 'root',
                password : '',
                port : 3306, //port mysql
                database:'nodejs'
            },'request')
        );//route index, hello world
        app.get('/', routes.index);//route customer list
        app.get('/customers', customers.list);//route add customer, get n post
        app.get('/customers/add', customers.add);
        app.post('/customers/add', customers.save);//route delete customer
        app.get('/customers/delete/:id', customers.delete_customer);//edit customer route , get n post
        app.get('/customers/edit/:id', customers.edit); 
        app.post('/customers/edit/:id',customers.save_edit);
        app.use(app.router);
        http.createServer(app).listen(app.get('port'), function(){
          console.log('Express server listening on port ' + app.get('port'));
        });

        remember to make new files/folder like shown on the above pic.

        Now, wee need codes to DO THE CRUD. the file's located routes/customers.js
        /*
         * GET customers listing.
         */
        exports.list = function(req, res){
          req.getConnection(function(err,connection){
               
             connection.query('SELECT * FROM customer',function(err,rows)     {
                    
                if(err)
                   console.log("Error Selecting : %s ",err );
             
                    res.render('customers',{page_title:"Customers - Node.js",data:rows});
                                   
                 });
               
            });
          
        };
        exports.add = function(req, res){
          res.render('add_customer',{page_title:"Add Customers-Node.js"});
        };
        exports.edit = function(req, res){
            
          var id = req.params.id;
            
          req.getConnection(function(err,connection){
               
             connection.query('SELECT * FROM customer WHERE id = ?',[id],function(err,rows)
                {
                    
                    if(err)
                        console.log("Error Selecting : %s ",err );
             
                    res.render('edit_customer',{page_title:"Edit Customers - Node.js",data:rows});
                                   
                 });
                         
            }); 
        };
        /*Save the customer*/
        exports.save = function(req,res){
            
            var input = JSON.parse(JSON.stringify(req.body));
            
            req.getConnection(function (err, connection) {
                
                var data = {
                    
                    name    : input.name,
                    address : input.address,
                    email   : input.email,
                    phone   : input.phone 
                
                };
                
                var query = connection.query("INSERT INTO customer set ? ",data, function(err, rows)
                {
          
                  if (err)
                      console.log("Error inserting : %s ",err );
                 
                  res.redirect('/customers');
                  
                });
                
               // console.log(query.sql); get raw query
            
            });
        };/*Save edited customer*/
        exports.save_edit = function(req,res){
            
            var input = JSON.parse(JSON.stringify(req.body));
            var id = req.params.id;
            
            req.getConnection(function (err, connection) {
                
                var data = {
                    
                    name    : input.name,
                    address : input.address,
                    email   : input.email,
                    phone   : input.phone 
                
                };
                
                connection.query("UPDATE customer set ? WHERE id = ? ",[data,id], function(err, rows)
                {
          
                  if (err)
                      console.log("Error Updating : %s ",err );
                 
                  res.redirect('/customers');
                  
                });
            
            });
        };
        
        exports.delete_customer = function(req,res){
                  
             var id = req.params.id;
            
             req.getConnection(function (err, connection) {
                
                connection.query("DELETE FROM customer  WHERE id = ? ",[id], function(err, rows)
                {
                    
                     if(err)
                         console.log("Error deleting : %s ",err );
                    
                     res.redirect('/customers');
                     
                });
                
             });
        };

        here's html code (ejs template) for listing the customer
        <%- include layouts/header.ejs %>
                <div class="page-data">
                 <div class="data-btn">
                   <button onClick="addUser();">+ Add</button>
                 </div>
                 <div class="data-table">
                    <table border="1" cellpadding="7" cellspacing="7">
                        <tr>
                            <th width="50px">No</th>
                            <th>Name</th>
                            <th>Address</th>
                            <th>Phone</th>
                            <th>Email</th>
                            <th width="120px">Action</th>
                        </tr>                               
                        <% if(data.length){ 
                                        
                         for(var i = 0;i < data.length;i++) { %>                 
                        <tr>
                            <td><%=(i+1)%></td>
                            <td><%=data[i].name%></td>
                            <td><%=data[i].address%></td>
                            <td><%=data[i].phone%></td>
                            <td><%=data[i].email%></td>
                            <td>
                                <a class="a-inside edit" href="../customers/edit/<%=data[i].id%>">Edit</a>                       
                                <a class="a-inside delete" href="../customers/delete/<%=data[i].id%>">Delete</a>                       
                            </td>
                        </tr>
                    <% }
                    
                     }else{ %>
                         <tr>
                            <td colspan="3">No user</td>
                         </tr>
                    <% } %>
                                                                     
                    </table>
                 </div>
                </div>        
        <%- include layouts/footer.ejs %>

        Well, actually 'm too lazy to put it all here...its gonna be a long scroll :(. pardon me for that. I think you can just download the Source here nodecrud and put a questions or issue on the Comment bellow. 

        run the the source code :
        ubuntu@AcerXtimeline:~/hello_world$ node app.js
        http://localhost:4300/customers
        

        The source will produce things like

        Screenshot from 2014-06-24 11:14:12



        Screenshot from 2014-06-24 11:16:26


        Notes : The version of express framework could be an issue, also newer express version may have different folder structure with the above, port it to your own version. The Node version of this example is v0.10.25, NPM 1.3.26 and express 3.5.1

        How to get data from MySQL with AngularJS – PHP

        How to get data from MySQL with AngularJS – PHP

        With only using AngularJS it is not possible to get data from MySQL database because it only handles Client side requests.
        You have to use any Server side language at backend which handles the request and returns response.

        In AngularJS $http service is use to send AJAX request


        Contents

        1. Table structure
        2. Configuration
        3. HTML
        4. PHP
        5. Script
        6. Conclusion



        1. Table structure

        I am using users table in the tutorial example.
        CREATE TABLE `users` (
          `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
          `fname` varchar(80) NOT NULL,
          `lname` varchar(80) NOT NULL,
          `username` varchar(80) NOT NULL
        ) ENGINE=InnoDB DEFAULT CHARSET=latin1;


        2. Configuration

        Create a new config.php file.
        Completed Code
        <?php
        
        $host = "localhost"; /* Host name */
        $user = "root"; /* User */
        $password = ""; /* Password */
        $dbname = "tutorial"; /* Database name */
        
        $con = mysqli_connect($host, $user, $password,$dbname);
        // Check connection
        if (!$con) {
         die("Connection failed: " . mysqli_connect_error());
        }


        3. HTML

        You can either download and include angular.min.js in the page or use CDN.
        <script src='https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js'></script>
        Define <body ng-app='myapp'> and <div ng-controller='userCtrl'> on the page.
        For displaying data create a <table> layout and specify ng-repeat directive on a row. Which loop through all available data in users property.
        Completed Code
        <!doctype html>
        <html>
         <head>
          <title>How to get data from MySQL with AngularJS - PHP</title>
          <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
         
         </head>
         <body ng-app='myapp'>
        
          <div ng-controller="userCtrl">
         
          <table >
         
          <tr>
          <th>First name</th>
          <th>Last name</th>
          <th>Username</th>
          </tr>
          
          <!-- Display records -->
          <tr ng-repeat="user in users">
          <td>{{user.fname}}</td>
          <td>{{user.lname}}</td>
          <td>{{user.username}}</td>
          </tr>
         
          </table>
          </div>
         
         </body>
        </html>

        4. PHP

        Create new getData.php file.
        From here return JSON Array which has user details (fname, lname, and username).
        Completed Code
        include 'config.php';
        
        $sel = mysqli_query($con,"select * from users");
        $data = array();
        
        while ($row = mysqli_fetch_array($sel)) {
         $data[] = array("fname"=>$row['fname'],"lname"=>$row['lname'],"username"=>$row['username']);
        }
        echo json_encode($data);


        5. Script

        Create new module and setup AJAX request in controller ( userCtrl ).
        • Path – Passing file name getData.php in url and set method to get.
        • Success – AJAX successfully callback handle by then where store reponse.data to $scope.users.
        At HTML end display data using ng-repeat directive.
        Completed Code
        <script>
        var fetch = angular.module('myapp', []);
        
        fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
         $http({
          method: 'get',
          url: 'getData.php'
         }).then(function successCallback(response) {
          // Store response data
          $scope.users = response.data;
         });
        }]);
        
        </script>


        6. Conclusion

        Angular provide $http service which helps to make an AJAX call to the server.
        Similar to jQuery AJAX request you can either send GET or POST type request. Within tutorial example, I send GET request from $http to fetch data from MySQL database in JSON format.

        Friday, 18 August 2017

        Content or design? What comes first and why designers should help create content for websites.

        Content or design?

        What comes first and why designers should help create content for websites.


        Starting a new web design project is as exciting as it is frightening. There are many unknowns, usually very little time and client expectations are piling up. Sometimes there is no brief, contact with the client is done by a middleman and information is scarce. You have an idea for the design but you still have too little information about the product to come up with something substantial. Stalemate.
        Can a designer work without a brief? Well… he shouldn’t. A brief becomes a point of reference — it’s your first contact with the project. It has the basic outline of what the website should be about, what the target audience is and what are the goals. If your client doesn’t provide you with something like this, it’s in your best interest to meet, talk about it and ask questions.
        What is the product? Washing powder. What does it do? It washes. How well does it work? The best. Why is it the best? Because it’s unique technology.What can I do with this washing powder? Clean whites and colors.
        Getting these basic pieces of information gives you enough knowledge to come up with ideas for information architecture, graphic elements and a basic narrative for the website. Don’t be afraid of asking questions, they will help you to avoid mistakes and come up with a better design.
        Information is king. It’s the core of your website — without it, it would just be a pretty shell, awesome looking but lacking practical application. As a designer, you create a design system that combines “ah that looks awesome” and “oh, that’s interesting information”, with “just two clicks and I can purchase this thing!” That’s good design — pixel perfect, informative, intuitive and obstacle free.
        Web design is about solving problems and the main problem is how we tell the story of a product, so people want to use it. That’s why typography, colors, illustrations and all the beautiful stuff is not providing answers to the problem; it is the means in which we present the outcome. Let’s focus on content first.
        That means content should not be the last stage in design, something to be filled in right before the launch. Content is the backbone of your site, and must be developed together with the visual design.
        So hold your horses, sit down, pull out a sheet of paper and think of the website’s architecture. Because if you focus too much on pixel perfect design too early in the process those decisions you make now will later rule the content. We don’t want that, we want our king (content) and queen (design) to gracefully walk down the path of success ;)

        You are the Alpha and architecture is Omega

        Not every company has access to a content strategist or information architect, so many times the designer shapes both. Often we create information architecture, user flow, and also help in developing content strategy with the marketing department. It’s not a chore, it’s part of our job, and as designers we cannot forget about the bigger picture — a website is not just an aesthetic form, it’s a system where content and design come together and influence each other.
        First, content framework can be established while we work on the basic website architecture. At this point, we set a basic navigation structure and an outline of the content of the pages. We make decisions on what order the links should be placed in and that sets the priority of the content because based on the gathered information we decided that the “technology” subpage is more important than “services.”
        Should a designer write content? It’s not your job, right? Well, not entirely. You, as a designer, have the responsibility to take risks and set your project on a course. You obviously will do this with the visual aspect in mind and you should do this with content as well. It’s enough that you just set a general direction for the content and the copywriter will take care of the rest. It might take some time but it will be worth the effort.
        Another solution is to wait for the content draft, which might take a long time and might not be what you had expected. Despite the quality of the content draft, it should be enough of a point of reference for you. At least you have something that you can work with as it gives you an idea about what the client thinks is important. The most common mistake is to just copy and paste this content into your design, adjusting your layout to fit those 5 paragraphs about how the product will disrupt the tech world while providing holistic solutions…. Nope, use that content to your advantage, it should be an inspiration for you; tweak it, suggest changes, use it as your proto-copy.
        Don’t just wait for the email with the final_final_www_COPY_07.doc as an attachment. It will come too late and it won’t be what you think it should be. Be engaged in content creation, see how it “fits” in your design, get feedback and implement. Designing a website and content is a process that requires both parties to be engaged and goal-oriented. This kind of engagement protects you from ending up with a generic, template-like website. Each project is different and you should treat it with custom care.
        Good UX takes the content and communication of the website to the next level. When content supports design and vice versa, it’s the effect of the collaboration of the designer and content creator. That is why the creation of content and design is a somewhat organic process, and not the waterfallmodel; it’s many iterations until you finally arrive at the one that is ready for launch.
        Is content more important than design, or the opposite? Maybe it’s great content that drives and inspires great design or maybe it’s the design vision that drives awesome content? Well, I would guess it’s both at the same time because only when the two (content and design) work together can you achieve balance in your project. Yes, the design draws attention and it lets users decide in a split second whether to stay or leave, but it’s the content along with the design that drives user engagement and conversion rate. One cannot exist without the other. Thou shalt remember!

        Design system

        Paragraphs, headlines and bullet points are not only text placeholders but they are important elements of design; their length, visual arrangement, hierarchy and meaning are part of a design system that you create for every project.
        Designing is understanding your subject (client, product, service) so you simply must know a lot about it — ask questions, analyze competitors, talk to product owners. Knowledge is the base of good design and will help you choose the right path for the visual aspect of your project. No doubt it will help you come up with guidelines for website content.
        Microcopy becomes part of UI
        A website is a sale/informative entity, therefore information and how it is presented is the goal of our work. Text with illustrative elements helps create or sustain product awareness. It also conveys information about the core values of a product. Website content is a broad term; it spans from general website narrative to headlines and informative paragraphs, but it is also those little words which make a difference. Never forget about paying attention to micro copy. It helps break the barrier between the website and user. It makes a website more human, direct and accessible.

        Lorem ipsum

        Using only Lorem ipsum will make your draft design hard to read, better to try come up with some content.
        For internal purposes lorem ipsum serves as text placeholders. I personally use it just to see how a 4 line paragraph will look next to that icon I was drawing for a couple hours. But what I have to know is, what is this icon illustrating? If I know that we are showing “payment security” and the client told me it’s state of the art encryption i don’t have to wait for the paragraph copy, I just have to make sure to leave maximum 4 lines plus a two-word headline.
        Your clients should never see Lorem Ipsum. It’s better to draft copy than meaningless gibberish. Remember that your clients sometimes are not able to “imagine” the intention of text.
        Lorem ipsum is just a helpful tool in web design; it should never be a substitute for creative content. Design with content in mind. Use lorem ipsum with low fidelity mockups, it will simply tell you that here you are giving some space for text.

        Stages of creating content — the most universal way

        1Kickoff meeting. Your first opportunity to hear out your client’s expectations. First and foremost you learn about the subject of the project and it is your time to ask all your questions.
        2Information architecture. It allows us to create a tree-like structure of a website where each page covers a different subject of our website, allowing us to block out sections of content. It gives us a rough look at what we want to talk about — nothing too specific but it is an important first outline of content — just like deciding on how many rooms your house will have.
        With each step your content and design should become more detailed.
        3Draft content. Once you have the architecture information it’s time to clarify the goals of your website and how the content of each subpage relates to one another. This part is crucial because it has to answer questions that users might have. Remember that you are helping design content for the user and their comprehension of the copy is a priority here. You can draw a simple wireframe of a website on a piece of paper and describe what content could go in individual sections, like here we should write about features because earlier we introduced the product. This can be used as a basic guideline for content.
        4Design fitting. Once we know the basic narrative of the website we can move from sketch to low fidelity design, which allows us to place ideas for content in the right position, e.g. designing sections, paragraphs, header, sub-headers, foreseeing places for icons and other elements. This is the time to experiment with ideas, decide on technological solutions and possible interactions (sliders, panels, animations, infographics etc.). For this stage you can use a wireframe tool like UX Pin or Balsamiq.
        5Design iteration. So you presented your current design ideas, you talked about interactive solutions, ideas for illustrations and so on. Now is the time to tweak the content, add micro-adjustments, scratch redundant elements, simplify text, add missing titles and so on.
        6High fidelity design. Time to pull up your sleeves and design the hell out of that website. At this stage the content is almost done; you and your team know exactly what the message is of your website, which allows you to come up with relevant design solutions and illustrations!
        7Final touches. Time to move stuff a pixel to the left and make the logo bigger.
        8Launch. The project is out there, free as a bird.
        9Gather data. Evaluate the content and design based on data and tests — the conclusions of this audit will lead you to the next step.
        10Design iteration. Incorporate what you have learned from your audit and optimize the website to achieve better engagement and conversion. But that’s a topic for another article…

        Like I mentioned earlier, designing a website is an organic process and the best way to move it forward is to engage the client in the process, ask lots of questions, and bounce many ideas off of them. The simplest way to do that is to organize workshops where you work together exchanging ideas, inspirations, quick wireframes and user stories. It’s faster and far more productive than sending a bunch of emails.
        I have gathered a few interesting articles on the subject of copywriting in the designing process that might be useful for further research. Hope you enjoy!

        Alternative content