Top Questions:

  • 5 years-11 months

    How to Connect with MySQLi or PDO Server through PHP

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    PHP you can easily do this using the mysqli_connect() function. All communication between PHP and the MySQL database server takes place through this connection. The basic syntaxes for connecting to MySQL using MySQLi and PDO extensions:

    Syntax: MySQLi, Procedural way
    $con = mysqli_connect("hostname", "username", "password", "database");
    Syntax: MySQLi, Object Oriented way
    $con = new mysqli("hostname", "username", "password", "database");
    Syntax: PHP Data Objects (PDO) way
    $pdo = new PDO("mysql:host=hostname;dbname=database", "username", "password"); 
    Example (mysqli)

    Perform queries against the database:
    <?php
    $con=mysqli_connect("localhost","your_user","your_password","your_db");
    // Check connection
    if(mysqli_connect_errno())
    {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    
    // Perform queries
    mysqli_query($con,"SELECT * FROM yourtable");
    mysqli_query($con,"INSERT INTO yourtable (FName,LName,Age)
    VALUES ('Glen','Quagmir',65)");
    
    mysqli_close($con);
    ?> 
    Example (PDO)

    Perform queries against the database:
    <?php
    $servername = "localhost";
    $username = "your_username";
    $password = "your_password";
    $dbname = "your_DBPDO";
    
    try {
        $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
        // set the PDO error mode to exception
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
        // prepare sql and bind parameters
        $stmt = $conn->prepare("INSERT INTO yourGuests (ftname, lname, email)
        VALUES (:ftname, :lname, :email)");
        $stmt->bindParam(':ftname', $firstname);
        $stmt->bindParam(':lname', $lastname);
        $stmt->bindParam(':email', $email);
    
        // insert a row
        $firstname = "John";
        $lastname = "Doe";
        $email = "john@domain.com";
        $stmt->execute();
    
        // insert another row
        $firstname = "Julie1";
        $lastname = "Dooley1";
        $email = "julie1@domain.com";
        $stmt->execute();
    
        echo "New records added successfully";
        }
    catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
    $conn = null;
    ?> 
     
  • 3 years-4 months

    Match date from two columns in mysql

    • Category : mysql
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    You can match two column value using this code

     SELECT * FROM booking WHERE id='1' AND (STR_TO_DATE(`from`, '%d-%m-%Y') <='2017-02-24' AND (STR_TO_DATE(`till`, '%d-%m-%Y') >='2017-02-24')) AND service='test' AND status='0'
  • 5 years-11 months

    How to get all wordpress categories sort by top post categories first

    • Category : wordpress
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    I have below code here. It's display that I want categories names with all details as well. This code to display top post categories first show.

    <?php
    $GLOBALS['uname'] = get_categories();
    define(_SYSTEM_, 'uname');
    class get_all_category_by_top_post {
        public function show() {
            $categories = $this->{_SYSTEM_};
            usort($categories,array($this,'sortByOrder'));
            return $categories;
        }
      public function sortByOrder($a, $b) {
         return $a->count < $b->count;
      }
        public function __get($d) {
            return $GLOBALS[$d];  
        }
    }
    $categories = new get_all_category_by_top_post();
    echo "<pre>";
    print_r($categories->show());
    ?>
  • 3 years-4 months

    Multiple Image Upload Using Codeigniter

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    Easy Multiple Image Using Codeigniter.

    if($_FILES['filename']['name']!='')
     {
           $image=array();
           $counts = count($_FILES['filename']['name']);
           $config['upload_path'] = APPPATH.'uploads/'; //create upload folder in application
                                                        // Give permission -R 777 to upload folder 
           $config['allowed_types'] = '*';
           $files = $_FILES;
           for($i=0; $i<$counts; $i  )
            {       
               if($_FILES['filename']['name'][$i]!='')
     { 
           $_FILES['filename']['name']= time().$files['filename']['name'][$i];
           $_FILES['filename']['type']= $files['filename']['type'][$i];
           $_FILES['filename']['tmp_name']= $files['filename']['tmp_name'][$i];
           $_FILES['filename']['error']= $files['filename']['error'][$i];
           $_FILES['filename']['size']= $files['filename']['size'][$i];
           $this->load->library('upload', $config);
           $this->upload->initialize($config);
           $upload= $this->upload->do_upload('familypicture');
           if($upload){
          $uu=$this->upload->data();
                $image[] =$uu['file_name'];
       }
             }
             }
       $fileToUpload = implode('|',$image);
    }
     
  • 5 years-11 months

    How do I sorting MySQL result by ages from the birthday date

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    MySQL sorting by age if your birthday like this 1974-05-15, 1974-05-28 (YEAR,MONTH,DATE)

    <?php
    $table_name="YOUR_TABLE_NAME";
    $column_name="birthdate";
    $age_from=15;
    $age_to=45;
    
    $con=mysqli_connect("localhost","my_user","my_password","my_db");
    // Check connection
    if (mysqli_connect_errno())
      {
      echo "Failed to connect to MySQL: " . mysqli_connect_error();
      }
    
    // Perform queries
    
    $sql="SELECT * FROM $table_name WHERE TIMESTAMPDIFF(YEAR, $column_name, CURDATE()) BETWEEN $age_from AND $age_to";
    $result=mysqli_query($con,$sql);
    
    
    // Associative array
    $row=mysqli_fetch_array($result,MYSQLI_ASSOC);
    printf ("%s (%s)\n",$row["id"],$row["name"]);
    
    // Free result set
    mysqli_free_result($result);
    
    mysqli_close($con);
    ?> 
  • 3 years-4 months

    Drag Drop multiple divs

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    you can drag drop all data between multiple divs

     <div id="1" dvSource dvSourceul">
    <ul id="dropul_1">
          <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" /> </li>
    </ul>
        </div>
    <div id="2">
    <ul id="dropul_2">
          <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" />
    <li class="drop"> <img alt="" src="images/Chrysanthemum.jpg" /> </li>
    </ul>
        </div>
    /********Jquery*********
    <script>
     $(function () {
                $("li.drop").draggable({
                    revert: "invalid",
                    refreshPositions: true,
                    drag: function (event, ui) {
                        ui.helper.addClass("draggable");
                       
                    },
                    stop: function (event, ui) {
                        if ($.ui.ddmanager.drop(ui.helper.data("draggable"), event)) {
                             ui.helper.removeClass("ui-draggable-dragging");
                             ui.helper.removeClass("draggable");
                        }
                        else {
                            //alert(" not dropped.");
                        }
                    }
                });
                $(".dvSourceul").droppable({
                    drop: function (event, ui ) {
                      var newId=event.target.id;
                      var aworkid=ui.draggable.attr('data-id');
                        ui.draggable.addClass("dropped");
                        $("#dropul_" newId).append(ui.draggable);
                        $.ajax({
                          type: "POST",
                          url: "update_work.php",
                          data:'id=' aworkid '&wrkid=' newId,
                          success: function(data){
                          // alert(data);
                          }
                          });
                    }
                });
            });
    
    </script>
  • 3 years-4 months

    Drag drop

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    Drag Drop your table's data using jQuery,Ajax,php and mysql

    /**********HTML PART START**************/
    
    <div class="x_content my-data" id="">
    
                      <table class="table table-bordered">
                        <thead>
                          <tr>
                            <th>#</th>
                            <th>Image</th>
                            <th>Category</th>
                            <th>Edit</th>
                            <th>Delete</th>
                          </tr>
                        </thead>
    <?php
      
      $query = "SELECT * FROM product ORDER BY pos ASC";
      $result = mysql_query($query) or die(mysql_error().': '.$query);
      if(mysql_num_rows($result)) {
    ?>
    <form id="dd-form" action="" method="post">
      <input type="checkbox" value="1" name="autoSubmit" id="autoSubmit" class="autoooo" checked/>
    <tbody id="sortable-list">
      <?php 
        $order = array();
        $i=1;
        while($row = mysql_fetch_assoc($result)) {
            $img=explode(",",$row['product_img']);
                           $img=explode(",",$row['product_img']);
    $catqry=mysql_fetch_array(mysql_query("select * from category where id='".$row['product_cat_id']."'"));
    $scatqry=mysql_fetch_array(mysql_query("select * from subcategory where id='".$row['product_subcat_id']."'"));
    
                           echo '<tr title="',$row['id'],'"><td>',$i,'</td><td><img src="',$img[0],'" height="50" width="50"></td><td>',$catqry['cat_name_eng'].'/'.$catqry['cat_name_china'],'</td><td><a href="?edit=',$row['id'],'"><i class="fa fa-pencil"></i></a></td><td><a href="?delete=',$row['id'],'" onclick="return confirm("Are you sure you want to delete")"><i class="fa fa-trash"></i></a></td></tr>';
          $order[] = $row['id'];
          $i  ;
        }
      ?>
    </tbody>
    <br />
    <input type="hidden" name="sort_order" id="sort_order" value="<?php echo implode(',',$order); ?>" />
    </form>
    <?php } ?>
    
    
                      </table>
    
                    </div>
                  </div>
            
            </div>
    <style type="text/css" media="screen">
    #sortable-list1   { padding:0; }
    #sortable-list1 tr  { padding:4px 8px; color:#000; cursor:move; list-style:none; width:100px; background:#ddd; margin:10px 0; border:1px solid #999; }
    #sortable-list1 tr td { text-align: center; }
    #message-box1   { padding:4px 8px; margin:0 0 14px 0; width:500px; }
    .autoooo{ display : none; }
    </style>
    /**********HTML PART END**************/
    /**********SCRIPT PART START**************/
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
      <script>
    /* when the DOM is ready */
    $(document).ready(function() {
    
      /* grab important elements */
      var sortInput = $('#sort_order');
      var submit = $('#autoSubmit');
      var messageBox = $('#message-box');
      var list = $('#sortable-list');
      /* create requesting function to avoid duplicate code */
      var request = function() {
      $.ajax({
      url: "drop_ajax.php",
      data:'sort_order='   sortInput[0].value   '&ajax='   submit[0].checked   '&do_submit=1&byajax=1',
      type: "POST",
      success: function(data) {
            window.location.reload();
      }
      });
      };
      /* worker function */
      var fnSubmit = function(save) {
       
        var sortOrder = [];
        list.children('tr').each(function(e){
          sortOrder.push($(this).data('id'));
        });
        sortInput.val(sortOrder.join(','));
       // console.log(sortInput.val());
        if(save) {
          request();
        }
      };
      /* store values */
      list.children('tr').each(function(e) {
        var tr = $(this);
        tr.data('id',tr.attr('title')).attr('title','');
      });
      /* sortables */
      list.sortable({
        opacity: 0.7,
        update: function() {
          fnSubmit(true);
        }
      });
      list.disableSelection();
    });
    </script>
    /**********SCRIPT PART END**************/
    /**********AJAX PART START**************/
    <?php
    include('config.php'); /include your db file here
    /* on form submission */
    if(isset($_POST['do_submit']))  {
      /* split the value of the sortation */
      $ids = explode(',',$_POST['sort_order']);
     /* run the update query for each id */
      foreach($ids as $index=>$id) {
       $id = (int) $id;
        if($id != '') {
         $query = 'UPDATE product SET pos = '.($index   1).' WHERE id = '.$id;
         $result = mysql_query($query) or die(mysql_error().': '.$query);
        }
     }
     
      /* now what? */
     if($_POST['byajax']) { die(); } else { $message = 'Sortation has been saved.'; 
     
      echo $message;
      }
    }
    ?>
    
    
    /**********AJAX PART END**************/
  • 3 years-4 months

    5 Star Rating Using php,ajax,jQuery

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    simple php rating in php

    <?php
    require "user/class.user.php";
    $auth_user = new USER();
    /********PDO Code***********/
    $email='user@gmail.com';
    $user=$auth_user->runQuery("SELECT * FROM login where email=:email");
    $user->execute(array(':email'=>$email));
    $userdatasingle=$user->fetchAll();
    $userdatasingle=$userdatasingle[0];
    ?>
    /*****HTML*******/
    <div class="rating">
                          
     <input type="hidden" name="rating" id="rating" value="<?php echo $userdatasingle["rating"]; ?>" />
           <ul onMouseOut="resetRating(<?php echo $userdatasingle["id"]; ?>);">
                 <?php
                 for($i=1;$i<=5;$i  ) {
                 $selected = "";
                 if(!empty($userdatasingle["rating"]) && $i<=$userdatasingle["rating"]) {
                 $selected = "selecteds";
                 }
         ?>
      <li class='<?php echo $selected; ?>' onmouseover="highlightStar(this,<?php echo $userdatasingle["id"]; ?>);" onmouseout="removeHighlight(<?php echo $userdatasingle["id"]; ?>);" onClick="addRating(this,<?php echo $userdatasingle["id"]; ?>);">&#9733;</li>  
                            <?php }  ?>
                        <ul>
                        <span class="ratings"><a href="#" class="Lgreen-txt font-6 rat-txt"><?php echo $userdatasingle["rating"]; ?> anmeldelser</a>
                       </span>
    </div> 
    /***********Script*************/
    <script>
    function highlightStar(obj,id) {
      removeHighlight(id);    
      $('.rating li').each(function(index) {
        $(this).addClass('highlights');
        if(index == $('.rating li').index(obj)) {
          return false; 
        }
      });
    }
    
    function removeHighlight(id) {
      $('.rating li').removeClass('selecteds');
      $('.rating li').removeClass('highlights');
    }
    
    function addRating(obj,id) {
      $('.rating li').each(function(index) {
        $(this).addClass('selecteds');
        $('#rating').val((index 1));
        if(index == $('.rating li').index(obj)) {
          return false; 
        }
      });
      $.ajax({
      url: "add_rating.php",
      data:'id=' id '&rate=' $('#rating').val(),
      type: "POST",
      success: function(data) {
      $(".rating").load(location.href " .rating>*","");
      }
      });
    }
    
    function resetRating(id) {
      if($('#rating').val() != 0) {
        $('.rating li').each(function(index) {
          $(this).addClass('selecteds');
          if((index 1) == $('#rating').val()) {
            return false; 
          }
        });
      }
    } 
    </script>
    /**********AJAX File*************/
    require "user/class.user.php";
    $auth_user = new USER();
    
    if (isset($_POST['rate']) && !empty($_POST['rate'])) {
     
        $rate = $_POST['rate'];
        $id = $_POST['id'];
    // check if user has already rated
        $sql = $auth_user->runQuery("UPDATE `login` SET rating=:rating WHERE `id`=:id");
       $sql->execute(array(':id'=>$id,':rating'=>$rate));
       
    }
     
  • 3 years-4 months

    Last Week Start And End Date

    • Category : php
    • Location : Chandigarh
    • Posted On :
    • Posted by : Guley

    Get last week start and end date in php

    $previous_week = strtotime("-1 week  1 day");
    
    $start_week = strtotime("last sunday midnight",$previous_week);
    $end_week = strtotime("next saturday",$start_week);
    
    $start_week = date("Y-m-d",$start_week);
    $end_week = date("Y-m-d",$end_week);
    
    echo $start_week.' '.$end_week ;
     
  • 5 years-11 months

    PHP mysql search multiple tables using a keyword

    • Category : php
    • Location : Chandigarh, India
    • Posted On :
    • Posted by : Vikas

    I have two tables in my database which are: user and event for PHP mysql search multiple tables using a keyword

    create table : event like
    CREATE TABLE IF NOT EXISTS `event` (
      `id` int(32) unsigned NOT NULL AUTO_INCREMENT,
      `email` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
      `event_name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    then create table : user like
    CREATE TABLE IF NOT EXISTS `user` (
      `id` int(32) unsigned NOT NULL AUTO_INCREMENT,
      `email` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
      `name` varchar(32) COLLATE utf8mb4_unicode_ci NOT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
    mysql query
    $query = "(SELECT name,email,'new_name' as type FROM user WHERE name LIKE '%te%') UNION (SELECT event_name,email,'new_event_name' as type FROM event WHERE event_name LIKE '%te%')";
    mysql_query($query);
    output
    name     email                 type
    denis terzo   abcd@gmail.it       new_name
    Andrea    abcddd.abcddd@gmail.com   new_name
    test    abcddd.vvvv@gmail.com     new_event_name
    test    abcddd.vvvv@gmail.com     new_event_name
    ram     abcddd.vvvv@gmail.com     new_name