Showing posts with label MySQL. Show all posts
Showing posts with label MySQL. Show all posts

Saturday, 28 December 2013

PHP MySQL Simple Delete using PDO in Bootstrap Tutorial

 Furqan Aziz |  28 Dec 2013 |  Tutorials
IntroductionPHP MySQL Simple Delete using PDO in Bootstrap Tutorial
Delete Statement is very common and used to Delete existing records in database table.PHP MySQL Simple Delete using PDO in Bootstrap is a tutorial in which we will learn how to delete data in database table using PDO (PHP Data Objects) prepared statements while using Bootstrap CSS Framework. We will create table fist and then insert some records in it, then we will create a form for delete. Then we will use Post method in form to send values to another page and then we will get values, bind them and use them in prepare statements. Finally we will show the success message if data Deleted successfully. This tutorial contains demo and source in which you can test INSERT, UPDATE and SELECT options at one place. We will learn
  • How to create a fruit list table for demo.
  • How to make a Connection Page.
  • How to prepare query for delete
  • How to bind values for query.
  • How to execute delete query.
  • How to show a success message for Delete.

Source Files and Folders Explanation

Source Code Folder contains many files and folders, below is the explanation of each files and folders.
  • sql.txt contains full database structure along with sample data.
  • index.php is a startup page which contains try it button.
  • AdminIndex.php is a page which has various options like INSERT, UPDATE, DELETE, SELECT buttons along with tables for showing data.
  • FruitDMy.php is about prepared query for Delete functionality.
  • configPDO.php is a file which will create connection with MySQL database.
  • footer.php is a file which contains footer bar and form for Fruit name delete.
  • assets folder contains necessary css files, icons, images and js files.

    Create Table and Sample Data

  1. We will create sample table in our database using sql.txt file which contains following table create queries and sample data for demo and test.
    • fruitsratelist table contains fields like Fruitname and its Rate.
    • CREATE TABLE IF NOT EXISTS `fruitsratelist` (
        `Fruitname` varchar(15) NOT NULL,
        `Rate` double NOT NULL
      ) ENGINE=MyISAM DEFAULT CHARSET=latin1;
    • INSERT INTO `fruitsratelist` (`Fruitname`, `Rate`) VALUES
      ('Apple', 70),
      ('Apple', 90),
      ('Mango', 60),
      ('Banana', 70),
      ('Strawberry', 80),
      ('Apple', 40),
      ('Lemon', 70),
      ('Kiwi', 80);

    Create Delete Button

  2. We will create a button for DELETE inside option side nav in AdminIndex.php page with id deleteit and set data-toggle as modal for showing reference DIV in a modal. We set button class as danger button.
    • <a href="#deleteit" data-toggle="modal" class="btn btn-danger">Delete</a>
      

    Create Form in Modal

  3. Modal will be open when Delete Button pressed which will display below form for Delete of Fruit Names. Form code is in footer.php page which is included in AdminIndex.php. This form contains fruit names in drop down select option for delete. When we press Delete Fruit Records Button it will send values as POST method to FruitDMy.php.
    • <div id="deleteit" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
      <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
      <h3 id="myModalLabel">Delete Fruit Name and Rates</h3>
      </div>
      <div class="modal-body">
      <form class="form-horizontal" method="post" action="FruitDMy.php">
      
      <div class="control-group">
      <label class="control-label" for="Fruitname1">Fruit Name</label>
      <div class="controls">
      <select name="Fruitname1" id="Fruitname1"  required="required">
      <option value="">Fruit Name</option>
      <?php
      include("configPDO.php");
      // We Will prepare SQL Query
      $STM = $dbh->prepare("SELECT DISTINCT  Fruitname FROM fruitsratelist");
      // bind parameters, Named parameters always start with colon(:)
      $STM->execute();
      // we will fetch records like this and use foreach loop to show multiple Results
      $STMrecords = $STM->fetchAll();
      foreach($STMrecords as $row)
      {
      echo"<option value='$row[0]'>$row[0]</option>"; 
      }      
      ?> 
      </select>
      
      </div>
      </div>
              
      
      <div class="control-group">
      <div class="controls">
      <input type="submit" name="submit" id="submit" class="btn btn-danger" value="Delete Fruit Records">
      </div>
      </div>
      </form>
      
      </div>
      </div>  
      

    Connect to Database

  4. configPDO.php file use a PDO (PHP Data Objects) for connecting MySQL Database.
    • <?php
      // mysql hostname
      $hostname = 'localhost';
      // mysql username
      $username = 'root';
      // mysql password
      $password = '';
      // Database Connection using PDO
      try {
      $dbh = new PDO("mysql:host=$hostname;dbname=YourDatabaseName", $username, $password);
          }
      catch(PDOException $e)
          {
          echo $e->getMessage();
          }
      ?>

    Prepare and Execute Delete Queries

  5. Now we will discuss our FruitDMy.php which is used for getting values from the form and then Delete these in database using PDO query.
    • <?php
      include('configPDO.php');
      if(isset($_POST["submit"])=="Delete Fruit Records")
      
      {
      // Define Variable
      $Fruitname1    =  $_POST[Fruitname1];     //Fruitname1
      
      // We Will prepare SQL Query
       $STM = $dbh->prepare("DELETE FROM fruitsratelist  WHERE Fruitname=:Fruitname1");
      // bind paramenters, Named paramenters alaways start with colon(:)
          $STM->bindParam(':Fruitname1', $Fruitname1);
      // For Executing prepared statement we will use below function
          $STM->execute(); 
      // We use header here for redirecting it to other page where we will show success message.    
      header( "location:AdminIndex.php?Fruitstatsdeleted=77083368");             
      }
      ?> 

    Prepared Queries Methods

    There are three various methods to write PDO queries.
    • In this Demo we used named parameters key with prepared statement. Binding parameter is must before execution using this method.
      • $STM = $dbh->prepare("DELETE FROM fruitsratelist  WHERE Fruitname=:Fruitname1");
        $STM->bindParam(':Fruitname1', $Fruitname1);
        $STM->execute();
        
      OR
    • Other method is to use unnamed parameters with question mark (?)
      • $STM = $dbh->prepare("DELETE FROM fruitsratelist  WHERE Fruitname=?");
        $STM->bindParam(1, $Fruitname1);
        $STM->execute();
        
      OR
    • Below method is without binding and it can make code ripe for SQL Injections.
      • $STM = $dbh->prepare("DELETE FROM fruitsratelist  WHERE Fruitname=$Fruitname1");
        $STM->execute();
        
    • For Getting how many records Deleted we can use rowcount() function.
      • $Records_Deleted= $STM->rowCount();
        

    Show Success Message

  6. After data Deleted We will redirected to Adminindex.php page where we will show success message using codes return from FruitDMy.php
    • if($_GET["Fruitstatsdeleted"]==77083368)  
      {
      echo "<div class='alert alert-error'>"; 
      echo "<button type='button' class='close' data-dismiss='alert'>×</button>"; 
      echo "<h4>Updated.</h4>"; 
      echo "Fruit Name and all it rates deleted from this Demo System."; 
      echo "</div>";
      }

    Tools Required

    We used following tools and technologies for developing PHP Simple Delete using PDO in Bootstrap Tutorial.
    • PHP as Server Side Scripting Language
    • MySQL as a Database.
    • Bootstrap as CSS Framework.
    • JQuery as a service.
    • jqBootstrapValidation for validating sign-in form.
    • phpMyAdmin for creating database and tables.
    • Sublime Text 2+ as a code editor.
    • XAMPP as a package for Apache web server, PHP and MySQL.
    • Google Chrome as a browser for testing.
    Thanks for reading. Enjoy and share with friends.

Conclusion

We hope you will like PHP Simple Delete using PDO in Bootstrap Tutorial and find it easy. We used latest PDO (PHP Data Objects) Prepared statements in this tutorial with Bootstrap CSS Framework for making this quickly. For any query/suggestions please send message on ourFacebook Page.

Friday, 18 October 2013

PHP-MySQL Ajax Jquery-UI Autocomplete in Bootstrap Tutorial


This tutorial will show you how to use Jquery UI Autocomplete in Bootsrap via PHP, MySQL and AJAX. You can use it anywhere else too easily.
  1. You will learn to make Jquery UI autocomplete working in Bootstrap via PHP, MySQL and Ajax.
  2. First create a simple form using below code or you can use your own search code. Please note id of input is searchg which will use later.
    • <form  class="navbar-form pull-left">
      <input class="span4" id="searchg" type="text" placeholder="Search">
      <button class="btn" type="button">Search</button>
      </form>
      
  3. Now Download JQuery UI from here and unzip it and put it in assets folder of bootstrap or anywhere you want. and put following lines before the </body> tag
    • <!--Jquery UI required links-->
      <script src="assets/js/jquery.js"></script>
      <script src="assets/ui/jquery.ui.core.js"></script>
      <script src="assets/ui/jquery.ui.widget.js"></script>
      <script src="assets/ui/jquery.ui.position.js"></script>
      <script src="assets/ui/jquery.ui.autocomplete.js"></script>
  4. Now put following Jquery UI css link before the </head> tag.
    • <!--Jquery UI css link-->
      <link rel="stylesheet" href="assets/ui/themes/ui-darkness/jquery.ui.all.css">
      
  5. Under Jquery UI required links you will write following code for showing autocomplete on input. We will get data from php page Get_Categories.php using JSON and use searchg id.
    • <script type="text/javascript">
      $(document).ready(function()
      {
                $.ajax({
                     url: 'Get_Categories.php',
                     type: 'POST',
                     dataType: 'json',
                     success: function(data){
                           $('#searchg').autocomplete(
                           {
                                 source: data,
                                 minLength: 1   
                           });
                     }
                });  
      });
      </script>
  6. Now on Get_Categories.php page you will write following code to get results from database and output JSON String.
    • <?php
      /*** mysql hostname ***/
      $hostname = 'localhost';
      /*** mysql username ***/
      $username = 'username';
      /*** mysql password ***/
      $password = 'password';
      // Database Connection
      $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
      // Query to get the usable locations
          $locale = $_GET['term'];
      $sql = "SELECT DISTINCT Category FROM `category` WHERE `Category` LIKE '%$locale%'";
      // Deifne array for products
       $Product_array = array();
         foreach ($dbh->query($sql) as $row)
              {
              $result = $row[0];
         // use arrray_push to store results
        array_push($Product_array, $result);
              }
      // put files in $jason and then echo it for getting in your page using Ajax.        
      $json = json_encode($Product_array);
      echo $json; 
      ?>
  7. Below is a code for MySQL Table, you can copy it and paste it in your query window inside database.
    • --
      -- Table structure for table `category`
      --
      CREATE TABLE IF NOT EXISTS `category` (
        `SrNo` int(11) NOT NULL AUTO_INCREMENT,
        `Category` varchar(50) NOT NULL,
        `SubCategory` varchar(100) NOT NULL,
        PRIMARY KEY (`SrNo`)
      ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=14 ;
      --
      -- Dumping data for table `category`
      --
      INSERT INTO `category` (`SrNo`, `Category`, `SubCategory`) VALUES
      (1, 'Electronics', 'Mobile'),
      (2, 'Electronics', 'Tablet'),
      (3, 'Electronics', 'IPad'),
      (4, 'Electronics', 'ITab'),
      (5, 'Electronics', 'Television'),
      (6, 'Electronics', 'Camera'),
      (7, 'Electronics', 'Laptop'),
      (8, 'Electronics', 'LCD'),
      (9, 'Electronics', 'Computer'),
      (10, 'Books', 'Magazines'),
      (11, 'Books', 'Journals'),
      (12, 'Books', 'Course Books'),
      (13, 'Garments', 'Kids Clothes');
Above tutorial is very useful for making autocomple function in web pages. You can also use some features of this tutorials. For more information please visit Crewow Website

Thursday, 17 October 2013

PHP Simple Sign-in Tutorial



This tutorial is about simple sign-in php code for beginners. You can also protect pages from unauthorized persons.
  1. You will learn to make one database table, one form , checking php page, user session page, config page and secret page.
  2. First create a simple form using below code or you can use your own sign in form.
    • <form  method="post" action="CheckLogin.php">
      <input type="email" name="inputEmail"  id="inputEmail" placeholder="Email">
      <input type="password" name="inputPassword" id="inputPassword" placeholder="Password" maxlength="15" minlength="6"  >
      <button type="submit" >Sign in</button>
      </form>
  3. Now you will run below SQL Code to make a simple table in your database.
    • CREATE TABLE IF NOT EXISTS `members` (
      `id` int(4) NOT NULL AUTO_INCREMENT,
      `name` varchar(65) NOT NULL DEFAULT '',
      `email` varchar(65) NOT NULL DEFAULT '',
      `password` varchar(65) NOT NULL DEFAULT '',
      `Type` varchar(10) NOT NULL,
      PRIMARY KEY (`id`)
      ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
  4. Now its time to connect to the database, so we will make database connection file config.php
    • <?php
      $con = mysql_connect("localhost","root","yourpaswword");
      if (!$con)
      {
      die('Could not connect: ' . mysql_error());
      }
      mysql_select_db("YourDbName", $con);
      ?>
  5. Now when form submitted it will go to CheckLogin.php page and here is code for page.
    • <?php
      // Start Session because we will save some values to session varaible.
      session_start();
      ob_start();
      // include config file for php connection
       include("config.php");
      // memebers table name
      $tbl_name="members";
      // Define $myusername and $mypassword
      $myusername=$_POST['inputEmail']; 
      $mypassword=$_POST['inputPassword']; 
      // To protect MySQL injection
      $myusername = stripslashes($myusername);
      $mypassword = stripslashes($mypassword);
      $myusername = mysql_real_escape_string($myusername);
      $mypassword = mysql_real_escape_string($mypassword);
      below query will check username and password exists in system or not
      $sql="SELECT * FROM $tbl_name WHERE email='$myusername' AND password='$mypassword'";
      $result=mysql_query($sql);
      // Mysql_num_row is used for counting table records
      $count=mysql_num_rows($result);
      // If result matched $myusername and $mypassword, table record must be equal to 1  
      if($count==1)
      {
       $sql2=mysql_query("SELECT Type,email,name FROM $tbl_name WHERE email='$myusername'");
       $row=mysql_fetch_row($sql2);
       $_SESSION[type]=$row[0];
       $_SESSION[myusername]=$row[1];
       $_SESSION[name]=$row[2];
      //Depending on type of user we will redirect to various pages  
       if($row[0] == 'abc')  { header( "location:http://localhost/abc.php");  }
       else if($row[0] == 'xyz')  { header( "location:http://localhost/xyz.php");  }
       else if($row[0] == 'Admin')  { header( "location:http://localhost/admin.php");  }
       else    {   header( "location:http://localhost/index.php");  }
      }
      else
      {
       header("location:http://localhost/index.php");
      }
      ob_end_flush();
      ?>
  6. Now on user pages like abc.php, xyz.php or admin.php your will write below lines on top of the page to make them protected.
    • <?php
      include('UserSession_xyz.php');
      ?>
  7. Below is code for UserSession_xyz.php. you will also make other pages for other users.
    • <?php
      session_start();
      if($_SESSION[type]!='xyz'){
      header('location:index.php');
      exit();
      }
      include('config.php');
      ?>
Above tutorial is very useful for making websites pages secure and make user Sing-In System. You can also use some features of this tutorials. For more information please visit Website: Crewow

Saturday, 28 September 2013

PHP Dynamic Select options Via Ajax


PHP Dynamic Select options Via Ajax is tutorial for those who want to make 2 dynamic select options in form. one is dependent on other and data fetched from MySQL Database.

Website for Complete Tutorial is Crewow




  1. Open your Dreamweaver or Notepad editor and create new PHP Page and name it myform.php
  2. Now Create only one Table for Categories like this
    • CREATE TABLE IF NOT EXISTS `category` (
        `SrNo` int(11) NOT NULL AUTO_INCREMENT,
        `Category` varchar(50) NOT NULL,
        `SubCategory` varchar(100) NOT NULL,
        PRIMARY KEY (`SrNo`)
      ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; 
  3. Now insert some sample values like this
    • INSERT INTO `category` (`SrNo`, `Category`, `SubCategory`) VALUES
      (1, 'Electronics', 'Mobile'),
      (2, 'Electronics', 'Tablet'),
      (3, 'Electronics', 'IPad'),
      (4, 'Electronics', 'ITab'),
      (5, 'Electronics', 'Television'),
      (6, 'Electronics', 'Camera'),
      (7, 'Electronics', 'Laptop'),
      (8, 'Electronics', 'LCD'),
      (9, 'Electronics', 'Computer'),
      (10, 'Books', 'Magazines'),
      (11, 'Books', 'Journals'),
      (12, 'Books', 'Course Books'); 
  4. In myform.php for making Category Field use below PHP Lines to get data from Category Table. please write these lines inside <form></form> tags.
    • <?php 
      echo "<select name='Category' id='Category'>";
      echo "<option value='' disabled='' selected='' >--Select Category--</option>"; 
      $q6=mysql_query("select DISTINCT Category from category");
      while($r6=mysql_fetch_array($q6))
      {
      echo "<option value='$r6[0]' >$r6[0]</option>"; 
      }
      echo "</select>";
      ?>
  5. Now make Sub Category select options like below. DO NOT Worry about Sub category options, we will load sub category via Ajax later.
    • <?php 
      echo "<select name='SubCategory' id='SubCategory'>";
      echo "<option value='' disabled='' selected='' >--Select Sub Category--</option>";  
      echo "</select>";
      ?>
  6. Now we need to make another PHP Page in which we will run query for sub category fields. Name it Ajax_SubCategory.php
    • <?php
      Config.php file for connecting to PHP.
      include('config.php');
      id will be posted via Ajax script. please see point no.7
      if($_POST['id'])
      {
      $id=$_POST['id'];
      $sql=mysql_query("select SubCategory from category where Category='$id'");
       while($row=mysql_fetch_array($sql))
       {
       $data=$row['SubCategory'];
       echo '<option value="'.$data.'">'.$data.'</option>';
       }
      }
      ?>
  7. Now we will call Ajax_SubCategory.php via Ajax and Jquery in myform.php. please includeJquery in your myform.php
    • <script type="text/javascript">
       $(document).ready(function(){
      Below line will get value of Category and store in id
      $("#Category").change(function()
      {
      var id=$(this).val();
      var dataString = 'id='+ id;
      $.ajax
      ({
      type: "POST",
      url: "Ajax_SubCategory.php",
      data: dataString,
      cache: false,
      success: function(html)
      {
      This will get values from Ajax_SubCategory.php and show in Subcategory Select option
      $("#SubCategory").html(html);
      } 
      });
      });       
       });
      </script>    
      
Above tutorial can be used for making dynamic select option or options. You can also use some features of this tutorials. For more information please visit Crewow | Free Website Tutorials

Saturday, 7 September 2013

CSV Importer in MySQL

CSV importer is a PHP file which can help you to import all your data in MySQL Database using CSV File. Source File csv_importer.php is also available with this tutorial.



Source File link is Here

  1. Open your Dreamweaver or Notepad editor and create new PHP Page and name it import.php
  2. Now include csv_importer.php file in your page like below.
    • include ( "csv_importer.php" );
  3. For Connecting MySQL Database please write following line
    • $conn = @mysql_connect("localhost","root","password");
  4. Now choose your database like below
    • @mysql_select_db("yourdbname",$conn);
  5. Now write below lines . you just need to provide your table name where you want to import data. leave all other lines as it is.
    • create new importer object for importing data
      $c = new CSV_Importer;
      display log errors at end           
      $c->log_errors = true;
      skip the very first row in CSV file         
      $c->skip_top   = true;
      Type of Server (default MYSQL), you can also use this  MSSQL and PGSQL          
      $c->server     = MYSQL; 
      Database Table where File will be imported         
      $c->table      = "yourtablename";
  6. Now you have to set columns of table according to your CSV file Template
    • $c->SetColumnSequence("Field1,Field2,Field3,Field4,Field5");
  7. Here you will write csv file reference from which your data will be imported to Table
    • $result = $c->import("Your_CSV_Name.csv",$conn);
  8. Now include csv_importer.php file in your page like below.
    • if($result === FALSE)
      {
      there was some error importing data
      $c->DumpErrors();
      }
      else
      {
      Your data imported successfully, it will print number of rows inserted.
      print "Total records inserted are $result in table $c->table";
      } 
  9. in the end you will close MySQL Connection
    • @mysql_close();
Above tutorial is based on scriptbaba 2009 scripts. Now that website is not working so I write this tutorial for you. For more information please open  Crewow Website