Tuesday, 31 May 2016

How to search multiple words at a time in Mysql php


If you want to learn how can search multiple words from Mysql table in a single query in php. You have show any web site there is on search textbox available for search data from that website. User enter the search query and it will result search result. This type of things we will learn in this post. For this things I have make one form with one textbox for entering search query and one button for search. When user click on search button use's request will send to server and on server side if user enter more than one words than that words will be converted into array by using explode() function and from that array I will make search string with mysql LIKE operator with that array and making complete search query for more than one words. In Video you can get get more information in details.

Source Code

Database


 --  
 -- Table structure for table `tbl_video`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_video` (  
  `video_id` int(11) NOT NULL AUTO_INCREMENT,  
  `video_title` varchar(300) NOT NULL,  
  `video_link` varchar(100) NOT NULL,  
  PRIMARY KEY (`video_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=40 ;  
 --  
 -- Dumping data for table `tbl_video`  
 --  
 INSERT INTO `tbl_video` (`video_id`, `video_title`, `video_link`) VALUES  
 (1, 'Export MySQL data to Excel in PHP - PHP Tutorial', 'http://www.google.com'),  
 (2, 'Live Table Add Edit Delete using Ajax Jquery in PHP Mysql', 'http://www.google.com'),  
 (3, 'Make SEO Friendly or Clean Url in PHP using .htaccess', 'http://www.google.com'),  
 (4, 'How to Add Watertext or Watermark to an Image using PHP GD Library', 'http://www.google.com'),  
 (5, 'Create Simple Image using PHP', 'http://www.google.com'),  
 (6, 'How to check Multiple value exists in an Array in PHP', 'http://www.google.com'),  
 (7, 'How to merge two PHP JSON Array', 'http://www.google.com'),  
 (8, 'How To Insert Data Using Stored Procedure In Php Mysql', 'http://www.google.com'),  
 (9, 'How to check Username availability using php, Ajax, Jquery and Mysql', 'http://www.google.com'),  
 (10, 'Rename uploaded image in php with upload validation', 'http://www.google.com'),  
 (11, 'How to generate simple random password in php?', 'http://www.google.com'),  
 (12, 'Auto Refresh Div Content Using jQuery and AJAX', 'http://www.google.com'),  
 (13, 'Insert Update Delete using Stored Procedure in Mysql and PHP', 'http://www.google.com');  

advance_search.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 if(isset($_POST["submit"]))  
 {  
      if(!empty($_POST["search"]))  
      {  
           $query = str_replace(" ", "+", $_POST["search"]);  
           header("location:advance_search.php?search=" . $query);  
      }  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Search multiple words at a time in Mysql php</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:500px;">  
                <h3 align="center">Search multiple words at a time in Mysql php</h3><br />  
                <form method="post">  
                     <label>Enter Search Text</label>  
                     <input type="text" name="search" class="form-control" value="<?php if(isset($_GET["search"])) echo $_GET["search"]; ?>" />  
                     <br />  
                     <input type="submit" name="submit" class="btn btn-info" value="Search" />  
                </form>  
                <br /><br />  
                <div class="table-responsive">  
                     <table class="table table-bordered">  
                     <?php  
                     if(isset($_GET["search"]))  
                     {  
                          $condition = '';  
                          $query = explode(" ", $_GET["search"]);  
                          foreach($query as $text)  
                          {  
                               $condition .= "video_title LIKE '%".mysqli_real_escape_string($connect, $text)."%' OR ";  
                          }  
                          $condition = substr($condition, 0, -4);  
                          $sql_query = "SELECT * FROM tbl_video WHERE " . $condition;  
                          $result = mysqli_query($connect, $sql_query);  
                          if(mysqli_num_rows($result) > 0)  
                          {  
                               while($row = mysqli_fetch_array($result))  
                               {  
                                    echo '<tr><td>'.$row["video_title"].'</td></tr>';  
                               }  
                          }  
                          else  
                          {  
                               echo '<label>Data not Found</label>';  
                          }  
                     }  
                     ?>  
                     </table>  
                </div>  
           </div>  
      </body>  
 </html>  

Saturday, 28 May 2016

PHP MySQL Insert record if not exists in table


In this PHP web development tutorial we will get knowledge on how to use mysql insert query for checking data already inserted or not. For this things we have use insert query with sub query with where condition and not exits. We have make simple insert query with select sub query with where not exists to check data already inserted or not in insert query. In old days, if you want to enter only unique data in particular column, then at that time before executing insert data query, you have first write select query for checking this data is present or not, but now we use WHERE NOT EXISTS and write sub query for this data is available in table or not. By this things we have to write only one query for checking data is already inserted or not. For more details, you can see video of this post.

Souce Code

Database


 --  
 -- Table structure for table `brand`  
 --  
 CREATE TABLE IF NOT EXISTS `brand` (  
  `brand_id` int(11) NOT NULL AUTO_INCREMENT,  
  `brand_name` varchar(250) NOT NULL,  
  PRIMARY KEY (`brand_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;  
 --  
 -- Dumping data for table `brand`  
 --  

data_already_inserted.php


 <?php  
 $connect = mysqli_connect("localhost", "root", "", "zzz");  
 $messsage = '';  
 if(isset($_POST["add"]))  
 {  
      if(!empty($_POST["brand"]))  
      {  
           $sql = "  
                INSERT INTO brand (brand_name)  
                SELECT '".$_POST["brand"]."' FROM brand  
                WHERE NOT EXIST(  
                 SELECT brand_name FROM brand WHERE brand_name = '".$_POST["brand"]."'  
                ) LIMIT 1  
           ";  
           if(mysqli_query($connect, $sql))  
           {  
                $insert_id = mysqli_insert_id($connect);  
                if($insert_id != '')  
                {  
                     header("location:data_already_inserted.php?inserted=1");  
                }  
                else  
                {  
                     header("location:data_already_inserted.php?already=1");  
                }  
           }  
      }  
      else  
      {  
           header("location:data_already_inserted.php?required=1");  
      }  
 }  
 if(isset($_GET["inserted"]))  
 {  
      $message = "Brand inserted";  
 }  
 if(isset($_GET["already"]))  
 {  
      $message = "Brand Already inserted";  
 }  
 if(isset($_GET["required"]))  
 {  
      $message = "Brand Name Required";  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | MySQL Insert record if not exists in table</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:500px;">  
                <label class="text-danger">  
                <?php  
                if($message!= '')  
                {  
                     echo $message;  
                }  
                ?>  
                </label>  
                <h3 align="">Insert Data</h3><br />                 
                <form method="post">  
                     <label>Enter Brand Name</label>  
                     <input type="text" name="brand" class="form-control" />  
                     <br />  
                     <input type="submit" name="add" class="btn btn-info" value="Add" />  
                </form>  
           </div>  
           <br />  
      </body>  
 </html>  

Tuesday, 24 May 2016

How to Make Simple Pagination using PHP MySql


Are you searching for simple PHP Pagination for a starting level of php programmer then you are at the correct place and This PHP pagination script or example is very well helpful to you. By using this PHP Script for Create Pagination with Previous and Next page link, First and Last page link also. Pagination is a style to make partition between content into different pages. Here we can define every pages as a separate URL. By click on that URL or number of that page, user can visit the content of that Page. For every page has number which is in incremental Page number. You can use this simple PHP pagination script or PHP pagination code into your project. For making simple pagination We have used PHP programming code with mysqli. We Hope with this PHP Pagination Tutorial using PHP MYSQL will be helpful to you to get the simple learning about the pagination as a beginner in php.



Source Code


pagination.php



<?php
$connect = mysqli_connect("localhost", "root", "", "testing");
$record_per_page = 5;
$page = '';
if(isset($_GET["page"]))
{
 $page = $_GET["page"];
}
else
{
 $page = 1;
}

$start_from = ($page-1)*$record_per_page;

$query = "SELECT * FROM tbl_student order by student_id DESC LIMIT $start_from, $record_per_page";
$result = mysqli_query($connect, $query);

?>

<!DOCTYPE html>
<html>
 <head>
  <title>Webslesson Tutorial | PHP Pagination with Next Previous First Last page Link</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <style>
  a {
   padding:8px 16px;
   border:1px solid #ccc;
   color:#333;
   font-weight:bold;
  }
  </style>
 </head>
 <body>
  <br /><br />
  <div class="container">
   <h3 align="center">PHP Pagination with Next Previous First Last page Link</h3><br />
   <div class="table-responsive">
    <table class="table table-bordered">
     <tr>
      <td>Name</td>
      <td>Phone</td>
     </tr>
     <?php
     while($row = mysqli_fetch_array($result))
     {
     ?>
     <tr>
      <td><?php echo $row["student_name"]; ?></td>
      <td><?php echo $row["student_phone"]; ?></td>
     </tr>
     <?php
     }
     ?>
    </table>
    <div align="center">
    <br />
    <?php
    $page_query = "SELECT * FROM tbl_student ORDER BY student_id DESC";
    $page_result = mysqli_query($connect, $page_query);
    $total_records = mysqli_num_rows($page_result);
    $total_pages = ceil($total_records/$record_per_page);
    $start_loop = $page;
    $difference = $total_pages - $page;
    if($difference <= 5)
    {
     $start_loop = $total_pages - 5;
    }
    $end_loop = $start_loop + 4;
    if($page > 1)
    {
     echo "<a href='pagination.php?page=1'>First</a>";
     echo "<a href='pagination.php?page=".($page - 1)."'><<</a>";
    }
    for($i=$start_loop; $i<=$end_loop; $i++)
    {     
     echo "<a href='pagination.php?page=".$i."'>".$i."</a>";
    }
    if($page <= $end_loop)
    {
     echo "<a href='pagination.php?page=".($page + 1)."'>>></a>";
     echo "<a href='pagination.php?page=".$total_pages."'>Last</a>";
    }
    
    
    ?>
    </div>
    <br /><br />
   </div>
  </div>
 </body>
</html>


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_student`
--

CREATE TABLE IF NOT EXISTS `tbl_student` (
  `student_id` int(11) NOT NULL AUTO_INCREMENT,
  `student_name` varchar(250) NOT NULL,
  `student_phone` varchar(20) NOT NULL,
  PRIMARY KEY (`student_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=51 ;

--
-- Dumping data for table `tbl_student`
--

INSERT INTO `tbl_student` (`student_id`, `student_name`, `student_phone`) VALUES
(1, 'Pauline S. Rich', '412-735-0224'),
(2, 'Sarah C. White', '320-552-9961'),
(3, 'Samuel L. Leslie', '201-324-8264'),
(4, 'Norma R. Manly', '478-322-4715'),
(5, 'Kimberly R. Castro', '479-966-6788'),
(6, 'Elaine R. Davis', '701-685-8912'),
(7, 'Concepcion S. Gardner', '607-829-8758'),
(8, 'Patricia J. White', '803-789-0429'),
(9, 'Michael M. Bothwell', '214-585-0737'),
(10, 'Ronald C. Vansickle', '630-571-4107'),
(11, 'Clarence A. Rich', '904-459-3747'),
(12, 'Elizabeth W. Peterson', '404-380-9481'),
(13, 'Renee R. Hewitt', '323-350-4973'),
(14, 'John K. Love', '337-229-1983'),
(15, 'Teresa J. Rincon', '216-394-6894'),
(16, 'Erin S. Huckaby', '503-284-8652'),
(17, 'Brian A. Handley', '989-304-7122'),
(18, 'Michelle A. Polk', '540-232-0351'),
(19, 'Wanda M. Brown', '718-262-7466'),
(20, 'Phillip A. Hatcher', '407-492-5727'),
(21, 'Dennis J. Terrell', '903-863-5810'),
(22, 'Britney F. Johnson', '972-421-6933'),
(23, 'Rachelle J. Martin', '920-397-4224'),
(24, 'Leila E. Ledoux', '615-425-9930'),
(25, 'Darrell A. Fields', '708-887-1913'),
(26, 'Linda D. Carter', '909-386-7998'),
(27, 'Melva J. Palmisano', '630-643-8763'),
(28, 'Jessica V. Windham', '513-807-9224'),
(29, 'Karen T. Martin', '847-385-1621'),
(30, 'Jack K. McDonough', '561-641-4509'),
(31, 'John M. Williams', '508-269-9346'),
(32, 'Amelia W. Davis', '347-537-8052'),
(33, 'Gertrude W. Lawrence', '510-702-7415'),
(34, 'Michael L. Harris', '252-219-4076'),
(35, 'Casey A. Groves', '810-334-9674'),
(36, 'James H. Wilson', '865-259-6772'),
(37, 'James A. Wesley', '443-217-1859'),
(38, 'Armando C. Gay', '716-252-9230'),
(39, 'James M. Duarte', '402-840-0541'),
(40, 'Jason E. West', '360-610-7730'),
(41, 'Gloria H. Saucedo', '205-861-3306'),
(42, 'Paul T. Moody', '914-683-4994'),
(43, 'Sandra L. Williams', '310-335-1336'),
(44, 'Elaine T. Deville', '626-513-8306'),
(45, 'Robyn L. Spangler', '754-224-7023'),
(46, 'Sam A. Pino', '806-823-5344'),
(47, 'Joseph H. Marble', '201-917-2804'),
(48, 'Mark M. Bassett', '206-592-4665'),
(49, 'Edgar M. Billy', '978-365-0324'),
(50, 'Connie M. Yang', '815-288-5435');

Tuesday, 17 May 2016

How to load Product on price change using Ajax Jquery with PHP Mysql


This post covers one more points on eCommerce site and it covers how to load product from two range of price using Ajax with JQuery PHP and Mysql. Suppose you have working on eCommerce site and you have display product on that page with price of that product. On that page you have use input type rand element for filtering product based on price. When user want to show product with less than particular price, so when user select price range then at that time only product load less than set price from database without refreshing of page. For this I have fetch product data from Mysql table by using Jquery Ajax() method with PHP code. When user change the price range from input type range element then at change event of range element then at time ajax method will be call and it will send request to server for fetching product with price less than selected of range of price. This whole things done withour refreshing event of page. You can get more description from Web development video tutorial which I have attached with this post.

Source Code

Product Table


 --  
 -- Table structure for table `product`  
 --  
 CREATE TABLE IF NOT EXISTS `product` (  
  `product_id` int(11) NOT NULL AUTO_INCREMENT,  
  `product_name` varchar(250) NOT NULL,  
  `brand_id` int(11) NOT NULL,  
  `product_price` float NOT NULL,  
  `product_image` varchar(150) NOT NULL,  
  PRIMARY KEY (`product_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=18 ;  
 --  
 -- Dumping data for table `product`  
 --  
 INSERT INTO `product` (`product_id`, `product_name`, `brand_id`, `product_price`, `product_image`) VALUES  
 (1, 'Samsung Galaxy A9', 1, 36000, 'Samsung_Galaxy_A9_L_1.jpg'),  
 (2, 'Samsung Galaxy S7', 1, 25000, 'samsung-galaxy-s7--.jpg'),  
 (3, 'Samsung Galaxy S6 edge', 1, 51000, 'Samsung-Galaxy-S6-Edge-32-SDL982046267-1-e60ad.jpg'),  
 (4, 'Xperia Z5 Premium', 2, 40000, 'Sony-Xperia-Z5-Premium-3.jpg'),  
 (5, 'Xperia M5 Dual', 2, 20000, '83201512213PM_635_sony_xperia_m5_dual.jpeg'),  
 (6, 'Xperia C5 uplta', 2, 15000, 'Sony-Xperia-C5-Ultra.jpg'),  
 (7, 'Moto G Turbo', 3, 10500, 'moto-g-turbo-black-540.png'),  
 (8, 'Moto X Force', 3, 35000, '1029201574637PM_635_moto_x_force.jpeg'),  
 (9, 'Redmi 3 Pro', 4, 12000, 'xiaomi-redmi-3-pro.png'),  
 (10, 'Mi 5', 4, 25000, '224201614903PM_635_xiaomi_mi_5_front_side.jpeg');  

html5_range.php


 <?php   
 $connect = mysqli_connect("localhost", "root", "", "zzz");  
 $query = "SELECT * FROM product ORDER BY product_price desc";  
 $result = mysqli_query($connect, $query);  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | How to load Product on price change using Ajax Jquery with PHP Mysql</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:800px;">  
                <br />  
                <h3 align="center">Load Product on price change using Ajax Jquery with PHP Mysql</h3>  
                <br />  
                <div align="center">  
                     <input type="range" min="10000" max="55000" step="1000" value="10000" id="min_price" name="min_price" />  
                     <span id="price_range"></span>  
                </div>  
                <br /><br /><br />  
                <div id="product_loading">  
                <?php  
                if(mysqli_num_rows($result) > 0)  
                {  
                     while($row = mysqli_fetch_array($result))  
                     {  
                ?>  
                <div class="col-md-4">  
                     <div style="border:1px solid #ccc; padding:12px; margin-bottom:16px; height:375px;" align="center">  
                          <img src="<?php echo $row["product_image"];?>" class="img-responsive" />  
                          <h3><?php echo $row["product_name"]; ?></h3>  
                          <h4>Price - <?php echo $row["product_price"]; ?></h4>  
                     </div>  
                </div>  
                <?php  
                     }  
                }  
                ?>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('#min_price').change(function(){  
           var price = $(this).val();  
           $("#price_range").text("Product under Price Rs." + price);  
           $.ajax({  
                url:"load_product.php",  
                method:"POST",  
                data:{price:price},  
                success:function(data){  
                     $("#product_loading").fadeIn(500).html(data);  
                }  
           });  
      });  
 });  
 </script>  

load_product.php


 <?php  
 //load_product.php  
 $connect = mysqli_connect("localhost", "root", "", "zzz");  
 if(isset($_POST["price"]))  
 {  
      $output = '';  
      $query = "SELECT * FROM product WHERE product_price <= ".$_POST['price']." ORDER BY product_price desc";  
      $result = mysqli_query($connect, $query);  
      if(mysqli_num_rows($result) > 0)  
      {  
           while($row = mysqli_fetch_array($result))  
           {  
                $output .= '  
                     <div class="col-md-4">  
                          <div style="border:1px solid #ccc; padding:12px; margin-bottom:16px; height:375px;" align="center">  
                               <img src="'.$row["product_image"].'" class="img-responsive" />  
                               <h3>'.$row["product_name"].'</h3>  
                               <h4>Price - '.$row["product_price"].'</h4>  
                          </div>  
                     </div>  
                ';  
           }  
      }  
      else  
      {  
           $output = "No Product Found";  
      }  
      echo $output;  
 }  
 ?>  

Sunday, 15 May 2016

PHP Login Script using OOP


Hi friends in this blog we will learn how to develop PHP Login script by using PHP Object Oriented Programming concept. If you are good php programmer then you definitely follows object oriented programming principals. It is mostly work with objects and easy to maintain your code. In this blog I like to describe how to create user login system by implementing PHP Object Oriented Programming. Here First I have create simple databases class and make database connection, I have write database connection code in construct() megic method of PHP OOP, this is because whenever new object of  this created this code will execute. After this I have make two function one for required field validation and other function will check the user enter correct information like username or password. This is my simple description, if you want to get more information, you can see the video of this post.


Source Code

database.php


 <?php   
 //database.php  
 class Databases{  
      public $con;  
      public $error;  
      public function __construct()  
      {  
           $this->con = mysqli_connect("localhost", "root", "", "testing");  
           if(!$this->con)  
           {  
                echo 'Database Connection Error ' . mysqli_connect_error($this->con);  
           }  
      }  
      public function required_validation($field)  
      {  
           $count = 0;  
           foreach($field as $key => $value)  
           {  
                if(empty($value))  
                {  
                     $count++;  
                     $this->error .= "<p>" . $key . " is required</p>";  
                }  
           }  
           if($count == 0)  
           {  
                return true;  
           }  
      }  
      public function can_login($table_name, $where_condition)  
      {  
           $condition = '';  
           foreach($where_condition as $key => $value)  
           {  
                $condition .= $key . " = '".$value."' AND ";  
           }  
           $condition = substr($condition, 0, -5);  
           /*This code will convert array to string like this-  
           input - array(  
                'id'     =>     '5'  
           )  
           output = id = '5'*/  
           $query = "SELECT * FROM ".$table_name." WHERE " . $condition;  
           $result = mysqli_query($this->con, $query);  
           if(mysqli_num_rows($result))  
           {  
                return true;  
           }  
           else  
           {  
                $this->error = "Wrong Data";  
           }  
      }       
 }  
 ?>  

can_login.php


 <?php  
 include 'database.php';  
 session_start();  
 $data = new Databases;  
 $message = '';  
 if(isset($_POST["login"]))  
 {  
      $field = array(  
           'username'     =>     $_POST["username"],  
           'password'     =>     $_POST["password"]  
      );  
      if($data->required_validation($field))  
      {  
           if($data->can_login("users", $field))  
           {  
                $_SESSION["username"] = $_POST["username"];  
                header("location:login_success.php");  
           }  
           else  
           {  
                $message = $data->error;  
           }  
      }  
      else  
      {  
           $message = $data->error;  
      }  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Login Form in PHP using OOP</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:500px;">  
                <h3 align="">Login Form in PHP using OOP</h3><br />  
                <?php  
                if(isset($message))  
                {  
                     echo '<label class="text-danger">'.$message.'</label>';  
                }  
                ?>  
                <form method="post">  
                     <label>Username</label>  
                     <input type="text" name="username" class="form-control" />  
                     <br />  
                     <label>Password</label>  
                     <input type="password" name="password" class="form-control" />  
                     <br />  
                     <input type="submit" name="login" class="btn btn-info" value="Login" />  
                </form>  
           </div>  
           <br />  
      </body>  
 </html>  

Friday, 13 May 2016

Delete Data from Mysql Table using OOP in PHP


I am continues on PHP Object Oriented Programming concept, here we will learn How to use PHP Object Oriented Programming for delete data from Mysql Table with confirmation message. As earlier post I have make one class in which I have already describe how to connect to database in OOPs, how to insert data into table, how to fetch data from table and how to update data using PHP OOPs. But Here I have show you how to delete data from Mysql table using PHP OOPs concept. For this things I have make one function delete with two parameter one is table name and is where condition. You can define table name and simply write where condition, from this two parameter it will generate delete query for remove data from table and execute that delete query. So this way this function is work, if want to get more information, you can learn in details from video also. 

Source Code

database.php



 <?php   
 //database.php  
 class Databases{  
      public $con;  
      public function __construct()  
      {  
           $this->con = mysqli_connect("localhost", "root", "", "testing");  
           if(!$this->con)  
           {  
                echo 'Database Connection Error ' . mysqli_connect_error($this->con);  
           }  
      }  
      public function insert($table_name, $data)  
      {  
           $string = "INSERT INTO ".$table_name." (";            
           $string .= implode(",", array_keys($data)) . ') VALUES (';            
           $string .= "'" . implode("','", array_values($data)) . "')";  
           if(mysqli_query($this->con, $string))  
           {  
                return true;  
           }  
           else  
           {  
                echo mysqli_error($this->con);  
           }  
      }  
      public function select($table_name)  
      {  
           $array = array();  
           $query = "SELECT * FROM ".$table_name."";  
           $result = mysqli_query($this->con, $query);  
           while($row = mysqli_fetch_assoc($result))  
           {  
                $array[] = $row;  
           }  
           return $array;  
      }  
      public function select_where($table_name, $where_condition)  
      {  
           $condition = '';  
           $array = array();  
           foreach($where_condition as $key => $value)  
           {  
                $condition .= $key . " = '".$value."' AND ";  
           }  
           $condition = substr($condition, 0, -5);  
           $query = "SELECT * FROM ".$table_name." WHERE " . $condition;  
           $result = mysqli_query($this->con, $query);  
           while($row = mysqli_fetch_array($result))  
           {  
                $array[] = $row;  
           }  
           return $array;  
      }  
      public function update($table_name, $fields, $where_condition)  
      {  
           $query = '';  
           $condition = '';  
           foreach($fields as $key => $value)  
           {  
                $query .= $key . "='".$value."', ";  
           }  
           $query = substr($query, 0, -2);  
           /*This code will convert array to string like this-  
           input - array(  
                'key1'     =>     'value1',  
                'key2'     =>     'value2'  
           )  
           output = key1 = 'value1', key2 = 'value2'*/  
           foreach($where_condition as $key => $value)  
           {  
                $condition .= $key . "='".$value."' AND ";  
           }  
           $condition = substr($condition, 0, -5);  
           /*This code will convert array to string like this-  
           input - array(  
                'id'     =>     '5'  
           )  
           output = id = '5'*/  
           $query = "UPDATE ".$table_name." SET ".$query." WHERE ".$condition."";  
           if(mysqli_query($this->con, $query))  
           {  
                return true;  
           }  
      }  
      public function delete($table_name, $where_condition)  
      {  
           $condition = '';  
           foreach($where_condition as $key => $value)  
           {  
                $condition .= $key . " = '".$value."' AND ";  
                /*This code will convert array to string like this-  
                input - array(  
                     'id'     =>     '5'  
                )  
                output = id = '5'*/  
                $condition = substr($condition, 0, -5);  
                $query = "DELETE FROM ".$table_name." WHERE ".$condition."";  
                if(mysqli_query($this->con, $query))  
                {  
                     return true;  
                }  
           }  
      }  
 }  
 ?>  


test_class.php


 <?php  
 //test_class.php  
 include 'database.php';  
 $data = new Databases;  
 $success_message = '';  
 if(isset($_POST["submit"]))  
 {  
      $insert_data = array(  
           'post_title'     =>     mysqli_real_escape_string($data->con, $_POST['post_title']),  
           'post_desc'          =>     mysqli_real_escape_string($data->con, $_POST['post_desc'])  
      );  
      if($data->insert('tbl_posts', $insert_data))  
      {  
           $success_message = 'Post Inserted';  
      }       
 }  
 if(isset($_POST["edit"]))  
 {  
      $update_data = array(  
           'post_title'     =>     mysqli_real_escape_string($data->con, $_POST['post_title']),  
           'post_desc'          =>     mysqli_real_escape_string($data->con, $_POST['post_desc'])  
      );  
      $where_condition = array(  
           'post_id'     =>     $_POST["post_id"]  
      );  
      if($data->update("tbl_posts", $update_data, $where_condition))  
      {  
           header("location:test_class.php?updated=1");  
      }  
 }  
 if(isset($_GET["updated"]))  
 {  
      $success_message = 'Post Updated';  
 }  
 if(isset($_GET["delete"]))  
 {  
      $where = array(  
           'post_id'     =>     $_GET["post_id"]  
      );  
      if($data->delete("tbl_posts", $where))  
      {  
           header("location:test_class.php?deleted=1");  
      }  
 }  
 if(isset($_GET["deleted"]))  
 {  
      $success_message = 'Post Deleted';  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Delete Data from Mysql Table using OOPS in PHP</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:700px;">  
                <form method="post">  
                     <?php  
                     if(isset($_GET["edit"]))  
                     {  
                          if(isset($_GET["post_id"]))  
                          {  
                               $where = array(  
                                    'post_id'     =>     $_GET["post_id"]  
                               );  
                               $single_data = $data->select_where("tbl_posts", $where);  
                               foreach($single_data as $post)  
                               {  
                     ?>  
                          <label>Post Title</label>  
                          <input type="text" name="post_title" value="<?php echo $post["post_title"]; ?>" class="form-control" />  
                          <br />  
                          <label>Post Description</label>  
                          <textarea name="post_desc" class="form-control"><?php echo $post["post_desc"]; ?></textarea>  
                          <br />  
                          <input type="hidden" name="post_id" value="<?php echo $post["post_id"]; ?>" />  
                          <input type="submit" name="edit" class="btn btn-info" value="Edit" />  
                     <?php  
                               }  
                          }  
                     }  
                     else  
                     {  
                     ?>  
                          <label>Post Title</label>  
                          <input type="text" name="post_title" class="form-control" />  
                          <br />  
                          <label>Post Description</label>  
                          <textarea name="post_desc" class="form-control"></textarea>  
                          <br />  
                          <input type="submit" name="submit" class="btn btn-info" value="Submit" />  
                     <?php  
                     }  
                     ?>  
                     <span class="text-success">  
                     <?php  
                     if(isset($success_message))  
                     {  
                          echo $success_message;  
                     }  
                     ?>  
                     </span>  
                </form>  
                <br />  
                <div class="table-responsive">  
                     <table class="table table-bordered">  
                          <tr>  
                               <td width="30%">Post Name</td>  
                               <td width="50">Post Description</td>  
                               <td width="10%">Edit</td>  
                               <td width="10%">Delete</td>  
                          </tr>  
                          <?php  
                          $post_data = $data->select('tbl_posts');  
                          foreach($post_data as $post)  
                          {  
                          ?>  
                          <tr>  
                               <td><?php echo $post["post_title"]; ?></td>  
                               <td><?php echo substr($post["post_desc"], 0, 200); ?></td>  
                               <td><a href="test_class.php?edit=1&post_id=<?php echo $post["post_id"]; ?>">Edit</a></td>  
                               <td><a href="#" id="<?php echo $post["post_id"]; ?>" class="delete">Delete</a></td>  
                          </tr>  
                          <?php  
                          }  
                          ?>  
                     </table>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      $('.delete').click(function(){  
           var post_id = $(this).attr("id");  
           if(confirm("Are you sure you want to delete this post?"))  
           {  
                window.location = "test_class.php?delete=1&post_id="+post_id+"";  
           }  
           else  
           {  
                return false;  
           }  
      });  
 });  
 </script>  

Thursday, 12 May 2016

Update or Edit Data from Mysql Table using OOPS in PHP

This is one more blog on crud database operation, here I will describe how to use php object oriented programming concept for edit or update data of mysql table. If you use PHP OOPs concept for programming then at later time you can easily maintain your code. You to change in one function then it will affect whole code where that was called. In previous post I have already created on class and in that class I have write many different function for different operation. For update of edit data using OOPs concept, I have create one function with name update with three parameter one is table name, second is the array of data in associative array format you want to update and third parameter is for where condition also in associative array. By using loop I will make update query and execute that query. This way this update function will work and We can use this function as many times. This way we can use PHP Object Oriented Programming concept for update or edit mysql data.

Source Code

database.php


 <?php   
 //database.php  
 class Databases{  
      public $con;  
      public function __construct()  
      {  
           $this->con = mysqli_connect("localhost", "root", "", "testing");  
           if(!$this->con)  
           {  
                echo 'Database Connection Error ' . mysqli_connect_error($this->con);  
           }  
      }  
      public function insert($table_name, $data)  
      {  
           $string = "INSERT INTO ".$table_name." (";            
           $string .= implode(",", array_keys($data)) . ') VALUES (';            
           $string .= "'" . implode("','", array_values($data)) . "')";  
           if(mysqli_query($this->con, $string))  
           {  
                return true;  
           }  
           else  
           {  
                echo mysqli_error($this->con);  
           }  
      }  
      public function select($table_name)  
      {  
           $array = array();  
           $query = "SELECT * FROM ".$table_name."";  
           $result = mysqli_query($this->con, $query);  
           while($row = mysqli_fetch_assoc($result))  
           {  
                $array[] = $row;  
           }  
           return $array;  
      }  
      public function select_where($table_name, $where_condition)  
      {  
           $condition = '';  
           $array = array();  
           foreach($where_condition as $key => $value)  
           {  
                $condition .= $key . " = '".$value."' AND ";  
           }  
           $condition = substr($condition, 0, -5);  
           $query = "SELECT * FROM ".$table_name." WHERE " . $condition;  
           $result = mysqli_query($this->con, $query);  
           while($row = mysqli_fetch_array($result))  
           {  
                $array[] = $row;  
           }  
           return $array;  
      }  
      public function update($table_name, $fields, $where_condition)  
      {  
           $query = '';  
           $condition = '';  
           foreach($fields as $key => $value)  
           {  
                $query .= $key . "='".$value."', ";  
           }  
           $query = substr($query, 0, -2);  
           /*This code will convert array to string like this-  
           input - array(  
                'key1'     =>     'value1',  
                'key2'     =>     'value2'  
           )  
           output = key1 = 'value1', key2 = 'value2'*/  
           foreach($where_condition as $key => $value)  
           {  
                $condition .= $key . "='".$value."' AND ";  
           }  
           $condition = substr($condition, 0, -5);  
           /*This code will convert array to string like this-  
           input - array(  
                'id'     =>     '5'  
           )  
           output = id = '5'*/  
           $query = "UPDATE ".$table_name." SET ".$query." WHERE ".$condition."";  
           if(mysqli_query($this->con, $query))  
           {  
                return true;  
           }  
      }  
 }  
 ?>  

test_class.php


 <?php  
 //test_class.php  
 include 'database.php';  
 $data = new Databases;  
 $success_message = '';  
 if(isset($_POST["submit"]))  
 {  
      $insert_data = array(  
           'post_title'     =>     mysqli_real_escape_string($data->con, $_POST['post_title']),  
           'post_desc'          =>     mysqli_real_escape_string($data->con, $_POST['post_desc'])  
      );  
      if($data->insert('tbl_posts', $insert_data))  
      {  
           $success_message = 'Post Inserted';  
      }       
 }  
 if(isset($_POST["edit"]))  
 {  
      $update_data = array(  
           'post_title'     =>     mysqli_real_escape_string($data->con, $_POST['post_title']),  
           'post_desc'          =>     mysqli_real_escape_string($data->con, $_POST['post_desc'])  
      );  
      $where_condition = array(  
           'post_id'     =>     $_POST["post_id"]  
      );  
      if($data->update("tbl_posts", $update_data, $where_condition))  
      {  
           header("location:test_class.php?updated=1");  
      }  
 }  
 if(isset($_GET["updated"]))  
 {  
      $success_message = 'Post Updated';  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Update or Edit Data from Mysql Table using OOPS in PHP</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:700px;">  
                <form method="post">  
                     <?php  
                     if(isset($_GET["edit"]))  
                     {  
                          if(isset($_GET["post_id"]))  
                          {  
                               $where = array(  
                                    'post_id'     =>     $_GET["post_id"]  
                               );  
                               $single_data = $data->select_where("tbl_posts", $where);  
                               foreach($single_data as $post)  
                               {  
                     ?>  
                          <label>Post Title</label>  
                          <input type="text" name="post_title" value="<?php echo $post["post_title"]; ?>" class="form-control" />  
                          <br />  
                          <label>Post Description</label>  
                          <textarea name="post_desc" class="form-control"><?php echo $post["post_desc"]; ?></textarea>  
                          <br />  
                          <input type="hidden" name="post_id" value="<?php echo $post["post_id"]; ?>" />  
                          <input type="submit" name="edit" class="btn btn-info" value="Edit" />  
                     <?php  
                               }  
                          }  
                     }  
                     else  
                     {  
                     ?>  
                          <label>Post Title</label>  
                          <input type="text" name="post_title" class="form-control" />  
                          <br />  
                          <label>Post Description</label>  
                          <textarea name="post_desc" class="form-control"></textarea>  
                          <br />  
                          <input type="submit" name="submit" class="btn btn-info" value="Submit" />  
                     <?php  
                     }  
                     ?>  
                     <span class="text-success">  
                     <?php  
                     if(isset($success_message))  
                     {  
                          echo $success_message;  
                     }  
                     ?>  
                     </span>  
                </form>  
                <br />  
                <div class="table-responsive">  
                     <table class="table table-bordered">  
                          <tr>  
                               <td width="30%">Post Name</td>  
                               <td width="50">Post Description</td>  
                               <td width="10%">Edit</td>  
                               <td width="10%">Delete</td>  
                          </tr>  
                          <?php  
                          $post_data = $data->select('tbl_posts');  
                          foreach($post_data as $post)  
                          {  
                          ?>  
                          <tr>  
                               <td><?php echo $post["post_title"]; ?></td>  
                               <td><?php echo substr($post["post_desc"], 0, 200); ?></td>  
                               <td><a href="test_class.php?edit=1&post_id=<?php echo $post["post_id"]; ?>">Edit</a></td>  
                               <td><a href="#" id="<?php echo $post["post_id"]; ?>" class="delete">Delete</a></td>  
                          </tr>  
                          <?php  
                          }  
                          ?>  
                     </table>  
                </div>  
           </div>  
      </body>  
 </html>  

Wednesday, 11 May 2016

Select or Fetch Data from Mysql Table using OOPS in PHP


In this post you can find how to use Object Oriented Programming concept of PHP to select or fetch data from Mysql database table. If you are beginner php programmer and you starting to learn PHP OOPs concept then this post is very useful. Here you can find how to create simple class, how to use php oops __construct() magic method, how to create simple function in class. Here you can learn select or fetch data from table using PHP OOPs. For this things I have create simple class with name databases and make database connection under __construct() magic method of PHP. This is because whenever new object is created of this class then at time which you have write under this method. For fetching data I have make one simple select function. You can called this function as many times. Because many advantage of OOPs is that reusable of code. You can use single function as many time. When you called this function then at that time you have to define only name of table from which you want to fetch data. This will reduce line of programming code. For more details, you can see the video of this post.

Source Code

database.php


 <?php   
 //database.php  
 class Databases{  
      public $con;  
      public function __construct()  
      {  
           $this->con = mysqli_connect("localhost", "root", "", "testing");  
           if(!$this->con)  
           {  
                echo 'Database Connection Error ' . mysqli_connect_error($this->con);  
           }  
      }  
      public function insert($table_name, $data)  
      {  
           $string = "INSERT INTO ".$table_name." (";            
           $string .= implode(",", array_keys($data)) . ') VALUES (';            
           $string .= "'" . implode("','", array_values($data)) . "')";  
           if(mysqli_query($this->con, $string))  
           {  
                return true;  
           }  
           else  
           {  
                echo mysqli_error($this->con);  
           }  
      }  
      public function select($table_name)  
      {  
           $array = array();  
           $query = "SELECT * FROM ".$table_name."";  
           $result = mysqli_query($this->con, $query);  
           while($row = mysqli_fetch_assoc($result))  
           {  
                $array[] = $row;  
           }  
           return $array;  
      }  
 }  
 ?>  

test_class.php


 <?php  
 //test_class.php  
 include 'database.php';  
 $data = new Databases;  
 $success_message = '';  
 if(isset($_POST["submit"]))  
 {  
      $insert_data = array(  
           'post_title'     =>     mysqli_real_escape_string($data->con, $_POST['post_title']),  
           'post_desc'          =>     mysqli_real_escape_string($data->con, $_POST['post_desc'])  
      );  
      if($data->insert('tbl_posts', $insert_data))  
      {  
           $success_message = 'Post Inserted';  
      }       
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Select or Fetch Data from Mysql Table using OOPS in PHP</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <body>  
           <br /><br />  
           <div class="container" style="width:700px;">  
                <form method="post">  
                     <label>Post Title</label>  
                     <input type="text" name="post_title" class="form-control" />  
                     <br />  
                     <label>Post Description</label>  
                     <textarea name="post_desc" class="form-control"></textarea>  
                     <br />  
                     <input type="submit" name="submit" class="btn btn-info" value="Submit" />  
                     <span class="text-success">  
                     <?php  
                     if(isset($success_message))  
                     {  
                          echo $success_message;  
                     }  
                     ?>  
                     </span>  
                </form>  
                <br />  
                <div class="table-responsive">  
                     <table class="table table-bordered">  
                          <tr>  
                               <td width="30%">Post Name</td>  
                               <td width="50">Post Description</td>  
                               <td width="10%">Edit</td>  
                               <td width="10%">Delete</td>  
                          </tr>  
                          <?php  
                          $post_data = $data->select('tbl_posts');  
                          foreach($post_data as $post)  
                          {  
                          ?>  
                          <tr>  
                               <td><?php echo $post["post_title"]; ?></td>  
                               <td><?php echo substr($post["post_desc"], 0, 200); ?></td>  
                               <td><a href="test_class.php?edit=1&post_id=<?php echo $post["post_id"]; ?>">Edit</a></td>  
                               <td><a href="#" id="<?php echo $post["post_id"]; ?>" class="delete">Delete</a></td>  
                          </tr>  
                          <?php  
                          }  
                          ?>  
                     </table>  
                </div>  
           </div>  
      </body>  
 </html>  

Saturday, 7 May 2016

How to Auto Resize a textarea html field by jQuery


This one more post on Web Development using JQuery, in this post we will discuss on auto resize of a html textarea field by using jquery. When user start type in html textarea element then it will automatically increase it's height very smoothly and when user will leave from textarea field it will automatically reduce the height smoothly and comes to it's orignal height. This all things are done by using jquery. By using jquery we can change the height of this fields. If you have use facebook and in facebook you have try type in textarea it was automatically change the height. If you want to give somethings new to your user then you can add this type of features in your web application. If you want to learn in details, you can see the video of this post.

Source Code


 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | How to Auto Resize a textarea with jQuery</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <style>  
           .wrapper{  
                width:500px;  
                margin:0 auto;  
           }  
           .resize{  
                height:40px;  
                padding:4px;  
                font-size:14px;  
                border:1px solid #dddddd;  
                width:100%;  
                border-radius:5px;  
           }  
           </style>  
           <script>  
           $(document).ready(function(){  
                $('.resize').focus(function(){  
                     $(this).animate({"height":"100px",}, "fast");  
                });  
                $('.resize').blur(function(){  
                     $(this).animate({"height": "40px",}, "fast" );  
                });  
           });  
           </script>  
      </head>  
      <body>  
           <div class="wrapper" align="center">  
                <br />  
                <h3>How to Auto Resize a textarea with jQuery</h3><br />  
                <textarea name="resize" class="resize"></textarea>  
                <br />  
           </div>  
      </body>  
 </html>  

Thursday, 5 May 2016

Stylish Switch Button using CSS3 and Jquery


Source Code




 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Stylish Switch Button using CSS3 and Jquery</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <style>  
           .wrapper{  
                width:500px;  
                margin:0 auto;  
           }  
           .switch{  
                width:200px;  
                height:100px;  
                background:#E5E5E5;  
                z-index:0;  
                margin:0;  
                padding:0;  
                appearance:none;  
                border:none;  
                cursor:pointer;  
                position:relative;  
                border-radius:100px;  
           }  
           .switch:before{  
                content: ' ';  
                position:absolute;  
                left:5px;  
                top:5px;  
                width:190px;  
                height:90px;  
                background:#FFFFFF;  
                z-index:1;  
                border-radius:95px;  
           }  
           .switch:after{  
                content:' ';  
                width:88px;  
                height:88px;  
                border-radius:86px;  
                z-index:2;  
                background:#FFFFFF;  
                position:absolute;  
                transition-duration:500ms;  
                top:6px;  
                left:6px;  
                box-shadow:0 2px 5px #999999;  
           }  
           .switchOn, .switchOn:before{  
                background:#4cd964; !important;  
           }  
           .switchOn:after{  
                left:105px;   
           }  
           </style>  
           <script>  
           $(document).ready(function(){  
                $('.switch').click(function(){  
                     $(this).toggleClass("switchOn");  
                });  
           });  
           </script>  
      </head>  
      <body>  
           <div class="wrapper" align="center">  
                <br />  
                <label>  
                     <input type="checkbox" name="switch" class="checkbox" />  
                     <div class="switch"></div>  
                </label>  
                <br />  
           </div>  
      </body>  
 </html>  

Tuesday, 3 May 2016

How to use Mysql View in PHP Code


This is most useful concept on Mysql database this is because in this post we have learn how to use of mysql view within php code. First of what is view. View is a virtual table based on result set of an sql statement. A view has rows and columns just like a real table. We can add fields in view from one or more tables in database. We can also use sql function and WHERE condition and even we can use JOIN statement in view. In this post for describing view I have join two tables. View can be create by using CREATE VIEW statement and then after writing simple query. View is store on to database table just like other tables. Suppose you want to called view from php code then you have to write simple select with name of view. This way you can called view from PHP code. In this post you can find source code under this post and for detail description you can also watch video of this post.


Create View

 CREATE view productlist AS SELECT brand.brand_name, product.product_name FROM brand INNER JOIN product ON product.brand_id = brand.brand_id  

Update View

 CREATE OR REPLACE view productlist AS SELECT brand.brand_id, brand.brand_name, product.product_name FROM brand INNER JOIN product ON product.brand_id = brand.brand_id  

mysql_view.php

 <?php  
 $connect = mysqli_connect("localhost", "root", "", "zzz");  
 $sql = "SELECT * FROM productlist";  
 $result = mysqli_query($connect, $sql);  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | How to use Mysql View in PHP Code</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:500px;">  
                <h3 align="">How to Use Mysql View in PHP Code</h3><br />                 
                <div class="table-responsive">  
                     <table class="table table-striped">  
                          <tr>  
                               <th>Brand ID</th>  
                               <th>Brand Name</th>  
                               <th>Product Name</th>  
                          </tr>  
                          <?php  
                          while($row = mysqli_fetch_array($result))  
                          {  
                          ?>  
                          <tr>  
                               <td><?php echo $row["brand_id"]; ?></td>  
                               <td><?php echo $row["brand_name"];?></td>  
                               <td><?php echo $row["product_name"]; ?></td>  
                          </tr>  
                          <?php  
                          }  
                          ?>  
                     </table>  
                </div>  
           </div>  
           <br />  
      </body>  
 </html>  

Upload and Extract a Zip File in Php


If you are looking to learn php advance concept like upload zip file and extract that file on server using php script. So in this post I will show you how to extract zip file in php and after from that uploaded file i will extract zip in upload folder after this I will copy all file from extracted folder to upload folder and remove zip file from upload folder and lastly remove extracted folder from upload file folder. I have show you one simple application, in which I want to upload images in very large amount for this I want to upload images in zip folder. From Zip folder I will extract zip folder and get images in to my upload directory and remove zip file and extracted folder. For this things I have use Zip Archive class and For this zip archive class first you have to enable php zip extension from php the list of php extension. I have create one zip object from Zip Archive class. You can find details description under video of this post.

Source Code

 <?php  
 if(isset($_POST["btn_zip"]))  
 {  
      $output = '';  
      if($_FILES['zip_file']['name'] != '')  
      {  
           $file_name = $_FILES['zip_file']['name'];  
           $array = explode(".", $file_name);  
           $name = $array[0];  
           $ext = $array[1];  
           if($ext == 'zip')  
           {  
                $path = 'upload/';  
                $location = $path . $file_name;  
                if(move_uploaded_file($_FILES['zip_file']['tmp_name'], $location))  
                {  
                     $zip = new ZipArchive;  
                     if($zip->open($location))  
                     {  
                          $zip->extractTo($path);  
                          $zip->close();  
                     }  
                     $files = scandir($path . $name);  
                     //$name is extract folder from zip file  
                     foreach($files as $file)  
                     {  
                          $file_ext = end(explode(".", $file));  
                          $allowed_ext = array('jpg', 'png');  
                          if(in_array($file_ext, $allowed_ext))  
                          {  
                               $new_name = md5(rand()).'.' . $file_ext;  
                               $output .= '<div class="col-md-6"><div style="padding:16px; border:1px solid #CCC;"><img src="upload/'.$new_name.'" width="170" height="240" /></div></div>';  
                               copy($path.$name.'/'.$file, $path . $new_name);  
                               unlink($path.$name.'/'.$file);  
                          }       
                     }  
                     unlink($location);  
                     rmdir($path . $name);  
                }  
           }  
      }  
 }  
 ?>  
 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | How to Extract a Zip File in Php</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <br />  
           <div class="container" style="width:500px;">  
                <h3 align="">How to Extract a Zip File in Php</h3><br />  
                <form method="post" enctype="multipart/form-data">  
                     <label>Please Select Zip File</label>  
                     <input type="file" name="zip_file" />  
                     <br />  
                     <input type="submit" name="btn_zip" class="btn btn-info" value="Upload" />  
                </form>  
                <br />  
                <?php  
                if(isset($output))  
                {  
                     echo $output;  
                }  
                ?>  
           </div>  
           <br />  
      </body>  
 </html>  

Monday, 2 May 2016

Convert Data from Mysql to JSON Formate using PHP


In PHP, Changing Data from MySQL to JSON type is one of the important a piece of work to be done in Web Development. JSON has obtained demand before the many years and it can be used over xml as data exchange format in web applications. By Using json format has its own benefits a like, it is being light weight, it has ability to store big type of data structures in simple text format and it has can be easily human readable. JSON is a data exchange format among web or mobile applications and it can be smoothly export data into plain text which can be human readable format and it can smoothly performance with any types of languages. Now I have show how to convert mysql data to json in php.

Database


 --  
 -- Table structure for table `tbl_employee`  
 --  
 CREATE TABLE IF NOT EXISTS `tbl_employee` (  
  `id` int(11) NOT NULL AUTO_INCREMENT,  
  `name` varchar(50) NOT NULL,  
  `gender` varchar(10) NOT NULL,  
  `designation` varchar(30) NOT NULL,  
  PRIMARY KEY (`id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;  
 --  
 -- Dumping data for table `tbl_employee`  
 --  
 INSERT INTO `tbl_employee` (`id`, `name`, `gender`, `designation`) VALUES  
 (1, 'Michael Bruce', 'Male', 'System Architect'),  
 (2, 'Jennifer Winters', 'Female', 'Senior Programmer'),  
 (3, 'Donna Fox', 'Female', 'Office Manager'),  
 (4, 'Howard Hatfield', 'Male', 'Customer Support');  


mysql_to_json.php


 <!DOCTYPE html>  
 <html>  
      <head>  
           <title>Webslesson Tutorial | Convert Data from Mysql to JSON Format using PHP</title>  
      </head>  
      <body>  
           <?php   
           $connect = mysqli_connect("localhost", "root", "", "testing");  
           $sql = "SELECT * FROM tbl_employee";  
           $result = mysqli_query($connect, $sql);  
           $json_array = array();  
           while($row = mysqli_fetch_assoc($result))  
           {  
                $json_array[] = $row;  
           }  
           /*echo '<pre>';  
           print_r(json_encode($json_array));  
           echo '</pre>';*/  
           echo json_encode($json_array);  
           ?>  
      </body>  
 </html>