Thursday, 14 November 2013

Freebie Complete PHP Project Bootstrap PDO Sign-In Jquery UI Autocomplete Validation


It is a freebie complete project for PHP beginners using PDO (PHP Data Objects) queries, Bootstrap, MySQL Database, JQuery UI, Jquery Validation Plug-in with full source code. Bootstrap CSS framework is used along with JQuery UI Autocomplete. For password change match password option is also good for users they want to design a sign up form. In server stats insertion form only double number allowed using regular expression. Jquery Validation plug-in used in this freebie project which works fine in all major browsers. It is a complete system , you can improve this and share with others. Enjoy it!
Click here for Details

Friday, 8 November 2013

Easy PHP Email With Attachments using Swift Mailer Tutorial


This tutorial is about sending email in PHP using Swift Mailer which is flexible and elegant object-oriented approach to send emails with a multitude of features. You can also attach files as Attachments. Enjoy it.
  1. Swift Mailer integrates into any web app written in PHP 5, offering a flexible and elegant object-oriented approach to sending emails with a multitude of features.
    • Send emails using SMTP, sendmail, postfix or a custom Transport implementation of your own.
    • Support servers that require username & password and/or encryption
    • Protect from header injection attacks without stripping request data content
    • Send MIME compliant HTML/multipart emails
    • Use event-driven plugins to customize the library
    • Handle large attachments and inline/embedded images with low memory use
  2. We will include swift mailer using below code.
    • // Swift Mailer library will be required. lib folder is available in source code.
      require_once 'lib/swift_required.php';
  3. Now we will include our connection configuration file like this if we want to include dynamic data from MySQL.
    • // For Dynamic contents we will add our config File
      include("configPDO.php");
      
  4. You will give SMTP Transport method here and provide details using below code for authentication.
    • // Create the Transport. we can put ip instead of smtp.example.org if we are on intranet.
      $transport = Swift_SmtpTransport::newInstance('smtp.example.org', 25)
        ->setUsername('your username')
        ->setPassword('your password')
        ;
  5. You could alternatively use a different transport such as Sendmail or Mail if required.
    • // Sendmail
      $transport = Swift_SendmailTransport::newInstance('/usr/sbin/sendmail -bs');
      // Mail
      $transport = Swift_MailTransport::newInstance();
  6. Now we will create the Mailer using created trasnport. please see below code, It will use later for sending message.
    • // Create the Mailer using your created Transport
      $mailer = Swift_Mailer::newInstance($transport);
  7. Now we will start creating our message. first we will choose our mesage subject.
    • // Subject of the Message
      $message = Swift_Message::newInstance('Subject is Crewow Free Web Tutorials');
  8. Sender Address will be written like this.
    • // Address of Sender will be written in setFrom Function
      $message->setFrom(array('info@crewow.com' => 'Furqan Aziz'));
  9. Receiver emails will be written like this.
    • // Address of the recipients will be written in setTo 
      $message->setTo(array('receiver@domain.org', 'other@domain.org' => 'A name'));
  10. We can add CC and BCC for this message like the below code.
    • // You can add CC like this.
      $message->addCc('info@crewow.com');
      // You can add BCC like this.
      $message->addbCc('someone@crewow.com');
  11. For Dynamic data we can either use query or variables which can be set.
    • // For Dynamic contents you will add your config File
      include("configPDO.php");
  12. Here is sample for just one variable which we will use in body of the message.
    • // Define $field1 and $field2 for named placeholders
      $field1= "Center"; 
      $field2="Active"; 
      We can use query to get results from MySQL Database using prepared query with PDO. Here its for $CToday only
      $STM = $dbh->prepare("SELECT SrNo FROM YourTable WHERE field1 = :field1 AND field2 = :field2");
      // bind paramenters, Named paramenters alaways start with colon(:)
      $STM->bindParam(':field1', $field1);
      $STM->bindParam(':field2', $field2);
      // For Executing prepared statement we will use below function
      $STM->execute();
      // Count no. of records
      $CToday = $STM->rowCount();
    OR
  13. We can set all variables manually or get them using POST method from some form.
    • // We can set variables like this
      $NToday = 200;  //North Today
      $CToday = 300;  //Central Today
      $SToday = 400;  //South Today
      $TotalToday = $NToday + $CToday + $SToday;  //Total Today
  14. Here is example of setting body for simplest message
    • // For Simple message we do like this
      $message->setBody('Here is the message itself');
    OR
  15. We can use HTML and CSS Style to make it attactive and cool
    • // For HTML/PHP message you can do it like this
      $message->setBody(
      '<html>' .
      ' <head><style type=text/css>
      * { margin: 0; padding: 0; }
      body { font: 14px Georgia, serif; }
      
      #page-wrap { width: 1024px; margin: 0 auto; }
      
      table { border-collapse: collapse; width: 100%; }
      td, th { border: 1px solid #0099FF; padding: 10px; }
      
      .slim { width: 88px; background-color: #eee;  }
      .hover { background-color: #eee; }
      </style></head>' .
      ' <body>' .
      ' <label>Dear Crewow Team,</label><br />
      <br />
      Here is our new Tutorial. please check below link after the table<br />
      <br /> <table>
      
       <tr>
       <td class=slim align=center ><strong>Region</strong></td>
          <td class=slim align=center ><strong>Today</strong></td>
       </tr>
       
           <tr>
          <td align=center>North</td>
       <td align=center>'.$NToday.'</td>
       </tr>
        
        <tr>
          <td align=center>Central</td>
       <td align=center>'.$CToday.'</td>
       </tr>
       
          <tr>
          <td align=center>South</td>
       <td align=center>'.$SToday.'</td>
       </tr>
          <tr>
          <td align=center><strong>Grand Total</strong></td>
       <td align=center><strong>'.$TotalToday.'</strong></td>
       </tr>
      </table>
      <br />
      <span style=color:#9966FF:><b><a href=http://crewow.com/>Crewo Website</a></b></span>
      <br /> 
      Best Regards<br />
      <hr>
      CreWow Network | www.crewow.com <br />
      
      <br />' .
      ' </body>' .
      '</html>',
        'text/html' //Mark the content-type as HTML
      );
  16. We can attach files using below code. please read swift mailer documentation for more details.
    • //Below code can be used to attached excel. you can attach any file you want like pdf zip or any other. 
      $message->attach(Swift_Attachment::fromPath('Excel/SampeFile.xls'));
  17. Finally we will send email message via created mailer like this.
    • // Send the message
      $result = $mailer->send($message);
You can use Swift mailer for sending emails. For any query/suggestions please post a comment on our Facebook Page.


Tuesday, 5 November 2013

Easy Pagination with PDO in PHP plus Export to Excel Tutorial

This tutorial will show you how to make pagination easily with PDO (PHP Data Objects) in PHP. Export to Excel additional feature is also available in this tutorial.
  1. First we will create test database for pagination using below query.
    • --
      -- Below query create PaginationTestDb Database
      --
      CREATE DATABASE  `PaginationTestDb` ;
  2. Now we will create table in PaginationTestDb using below code. More sample data is available in CreateTableandDatasample.sql file which is available in Source Code.
    • CREATE TABLE IF NOT EXISTS `statstracker` (
        `SrNo` int(11) NOT NULL AUTO_INCREMENT,
        `ServerName` varchar(15) NOT NULL,
        `HiMemUti` double NOT NULL,
        `AvgMemUti` double NOT NULL,
        `HiCpuUti` double NOT NULL,
        `AvgCpuUti` double NOT NULL,
        `HiIOPerSec` double NOT NULL,
        `AvgIOPerSec` double NOT NULL,
        `HiDiskUsage` double NOT NULL,
        `AvgDsikUsage` double NOT NULL,
        `EntryBy` varchar(15) NOT NULL,
        `EntryDate` date NOT NULL,
        PRIMARY KEY (`SrNo`),
        UNIQUE KEY `SrNo` (`SrNo`)
      ) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=15;
      -- Dumping data for table `statstracker`
      INSERT INTO `statstracker` (`SrNo`, `ServerName`, `HiMemUti`, `AvgMemUti`, `HiCpuUti`, `AvgCpuUti`, `HiIOPerSec`, `AvgIOPerSec`, `HiDiskUsage`, `AvgDsikUsage`, `EntryBy`, `EntryDate`) VALUES
      (1, '10.86.0.44', 98, 98, 98, 98, 98, 98, 98, 98, 'furqan.aziz', '2013-11-04'),
      (2, '10.86.0.75', 98, 96, 97, 90, 97, 94, 98, 90, 'furqan.aziz', '2013-11-05'),
      (3, '10.86.0.44', 95, 90, 92, 89, 93, 92, 94, 88, 'furqan.aziz', '2013-11-05'),
      (4, '10.86.0.66', 97, 97, 93, 88, 94, 92, 93, 93, 'furqan.aziz', '2013-11-05'),
      (5, '10.86.0.61', 12, 12, 12, 12, 12, 12, 12, 12, 'furqan.aziz', '2013-11-05'),
      (6, '10.86.0.44', 98, 98, 98, 98, 98, 98, 98, 98, 'furqan.aziz', '2013-11-04'),
      (7, '10.86.0.75', 98, 96, 97, 90, 97, 94, 98, 90, 'furqan.aziz', '2013-11-05'),
      (8, '10.86.0.44', 95, 90, 92, 89, 93, 92, 94, 88, 'furqan.aziz', '2013-11-05'),
      (9, '10.86.0.66', 97, 97, 93, 88, 94, 92, 93, 93, 'furqan.aziz', '2013-11-05'),
      (10, '10.86.0.61', 12, 12, 12, 12, 12, 12, 12, 12, 'furqan.aziz', '2013-11-05'),
      (11, '10.86.0.44', 98, 98, 98, 98, 98, 98, 98, 98, 'furqan.aziz', '2013-11-04'),
      (12, '10.86.0.75', 98, 96, 97, 90, 97, 94, 98, 90, 'furqan.aziz', '2013-11-05'),
      (13, '10.86.0.44', 95, 90, 92, 89, 93, 92, 94, 88, 'furqan.aziz', '2013-11-05'),
      (14, '10.86.0.66', 97, 97, 93, 88, 94, 92, 93, 93, 'furqan.aziz', '2013-11-05'),
      (15, '10.86.0.61', 12, 12, 12, 12, 12, 12, 12, 12, 'furqan.aziz', '2013-11-05');
  3. In this tutorial we have following files and resources. After you have download source code and unzip source, you will create database and table using above queries or using CreateTableandDatasample.sql. then you will put PAGINATIONPDO folder inside htdocs or www root and then test in browser.
    • CreateDatabase.txt contains create test database query.
    • CreateTableandDatasample.sql contains create table query and sample insert data query.
    • index.php is main file which has pagination code.
    • ExportToExcel.php is used to export all data in excel for specific user.
    • img folder contains export to excel PNG file.
    • css folder contains pagination.css file which have pagination style, table style and export to excel position style.
    • css folder contains Extra.css file having more styles Thanks to MIS ALGORITMOS.
  4. Here is index.php file code
    •  <!DOCTYPE html>
      <html lang="en">
        <head>
          <meta charset="utf-8">
          <title>Simple Pagination Demo using PDO Query</title>
              <!-- CSS File -->
          <link href="css/pagination.css" rel="stylesheet">
        </head>
       <body>
      <?php
       // mysql hostname
       $hostname = 'localhost';
       // mysql username
       $username = 'root';
       // mysql password
       $password = '';
       // Database Connection using PDO with try catch method. 
       try { $dbh = new PDO("mysql:host=$hostname;dbname=PaginationTestDb", $username, $password); }
       // In case of error PDO exception will show error message.
       catch(PDOException $e) {    echo $e->getMessage();    }
       // No. of adjacent pages shown on each side
       $adjacents = 2;
       // We will assign variable here for entry By. you can use your variables here.
       $EntryBy = "furqan.aziz";
       // We Will prepare SQL Query
          $STM = $dbh->prepare("SELECT ServerName FROM statstracker WHERE EntryBy = :EntryBy");
       // bind paramenters, Named paramenters alaways start with colon(:)
          $STM->bindParam(':EntryBy', $EntryBy);
       // For Executing prepared statement we will use below function
          $STM->execute();
       // Count no. of records
       $Records = $STM->rowCount();
       // Your File Name will be the same like your php page name which is index.php
       $targetpage = "index.php";
       // Below is setting for no. of records per page.
       $limit = 10; 
       $page = $_GET['page'];
       if($page) 
       //First Item to dipaly on this page
        $start = ($page - 1) * $limit;    
       else
       //if no page variable is given, set start to 0
        $start = 0;        
       // Get data using PDO prepare Query.
       $STM2 = $dbh->prepare("SELECT `SrNo`, `ServerName`, `HiMemUti`, `AvgMemUti`, `HiCpuUti`, `AvgCpuUti`, `HiIOPerSec`, `AvgIOPerSec`, `HiDiskUsage`, `AvgDsikUsage`, `EntryBy` FROM statstracker WHERE EntryBy = :EntryBy ORDER BY SrNo LIMIT $start, $limit");
       // bind paramenters, Named paramenters alaways start with colon(:)
          $STM2->bindParam(':EntryBy', $EntryBy);
       // For Executing prepared statement we will use below function
          $STM2->execute();
       // We will fetch records like this and use foreach loop to show multiple Results later in bottom of the page.
        $STMrecords = $STM2->fetchAll();
       // Setup page variables for display. If no page variable is given, default to 1.
       if ($page == 0) $page = 1;
       //previous page is page - 1     
       $prev = $page - 1;
       //next page is page + 1     
       $next = $page + 1;
       //lastpage is = total Records / items per page, rounded up.      
       $lastpage = ceil($Records/$limit);
       //last page minus 1 
       $lpm1 = $lastpage - 1;      
       //Now we apply our rules and draw the pagination object. We're actually saving the code to a variable in case we want to draw it more than once.
       $pagination = "";
       if($lastpage > 1)
       { 
        $pagination .= "<div class='pagination'>";
        //previous button
        if ($page > 1) 
         $pagination.= "<a href='$targetpage?page=$prev'>Previous</a>";
        else
         $pagination.= "<span class='disabled'>Previous</span>"; 
        
        //pages 
        if ($lastpage < 7 + ($adjacents * 2)) //not enough pages to bother breaking it up
        { 
         for ($counter = 1; $counter <= $lastpage; $counter++)
         {
          if ($counter == $page)
           $pagination.= "<span class='current'>$counter</span>";
          else
           $pagination.= "<a href='$targetpage?page=$counter'>$counter</a>";     
         }
        }
        elseif($lastpage > 5 + ($adjacents * 2)) //enough pages to hide some
        {
         //close to beginning; only hide later pages
         if($page < 1 + ($adjacents * 2))  
         {
          for ($counter = 1; $counter < 4 + ($adjacents * 2); $counter++)
          {
           if ($counter == $page)
            $pagination.= "<span class='current'>$counter</span>";
           else
            $pagination.= "<a href='$targetpage?page=$counter'>$counter</a>";     
          }
          $pagination.= "...";
          $pagination.= "<a href='$targetpage?page=$lpm1'>$lpm1</a>";
          $pagination.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";  
         }
         //in middle; hide some front and some back
         elseif($lastpage - ($adjacents * 2) > $page && $page > ($adjacents * 2))
         {
      
          $pagination.= "<a href='$targetpage?page=1'>1</a>";
          $pagination.= "<a href='$targetpage?page=2'>2</a>";
          $pagination.= "...";
          for ($counter = $page - $adjacents; $counter <= $page + $adjacents; $counter++)
          {
           if ($counter == $page)
            $pagination.= "<span class='current'>$counter</span>";
           else
            $pagination.= "<a href='$targetpage?page=$counter'>$counter</a>";     
          }
          $pagination.= "...";
          $pagination.= "<a href='$targetpage?page=$lpm1'>$lpm1</a>";
          $pagination.= "<a href='$targetpage?page=$lastpage'>$lastpage</a>";  
         }
         //close to end; only hide early pages
         else
         {
          $pagination.= "<a href='$targetpage?page=1'>1</a>";
          $pagination.= "<a href='$targetpage?page=2'>2</a>";
          $pagination.= "...";
          for ($counter = $lastpage - (2 + ($adjacents * 2)); $counter <= $lastpage; $counter++)
          {
           if ($counter == $page)
            $pagination.= "<span class='current'>$counter</span>";
           else
            $pagination.= "<a href='$targetpage?page=$counter'>$counter</a>";     
          }
         }
        }
        
        //next button
        if ($page < $counter - 1) 
         $pagination.= "<a href='$targetpage?page=$next'>Next</a>";
        else
         $pagination.= "<span class='disabled'>Next</span>";
        $pagination.= "</div>\n";  
       }
       //Below is a start of table in which we will show records using foreach loop.
       echo "<table class='mytableP'>";
       // For Exporting Records to Excel we will send $EntryBy in link and will gate it on ExportToExcel page for stats for this user. 
       echo"<tr><th th colspan=11>Simple Pagination Demo using PDO Quries</div></th></tr>";
       echo"<a href='ExportToExcel.php?val=$EntryBy' target=_blank><img src='img/e2e.png' alt='Export To Excel' border='' class='e2e' /></a>";
       echo"<tr><th>Sr#</th><th>Server</th><th>Hi Memory Utilization</th><th>Avg Memory Utilization</th><th>Hi CPU Utilization</th><th>Avg CPU Utilization</th><th>Hi I/O Utilization</th><th>Avg I/O Utilization</th><th>Hi Disk Usage</th><th>Avg Disk Usage</th><th>By</th></tr>";
          // We use foreach loop here to echo records.
       foreach($STMrecords as $r)
              {
         echo "<tr>";
            echo "<td>" .$r[0] ."</td>";
               echo "<td>" .$r[1] ."</td>";
            echo "<td>" .$r[2] ."</td>";
            echo "<td>" .$r[3] ."</td>";
            echo "<td>" .$r[4] ."</td>";
            echo "<td>" .$r[5] ."</td>";
            echo "<td>" .$r[6] ."</td>";
            echo "<td>" .$r[7] ."</td>";
            echo "<td>" .$r[8] ."</td>";
            echo "<td>" .$r[9] ."</td>";
            echo "<td>" .$r[10] ."</td>";
          echo "</tr>";  
        }
       echo "</table>";
       // For showing pagination below the table we will echo $pagination here after </table>. For showing above the table we will echo $pagination before <table>
       echo $pagination;
       // Closing MySQL database connection   
          $dbh = null;
       ?>
        </body>
      </html> 
      
  5. Below is the css Style which is used for pagination.
    • div.pagination {text-align:center;margin:3px;padding:3px;}
      div.pagination a {margin-right:2px;border:1px solid #2C2C2C;text-decoration:none;color:#fff;background:#2C2C2C;padding:2px 5px;}
      div.pagination a:hover,div.pagination a:active {border:1px solid #AAD83E;color:#FFF;background:#AAD83E;}
      div.pagination span.current {margin-right:2px;border:1px solid #AAD83E;font-weight:700;background:#AAD83E;color:#FFF;padding:2px 5px;}
      div.pagination span.disabled {margin-right:2px;border:1px solid #f3f3f3;color:#ccc;padding:2px 5px;}
  6. For table we used below style code
    • .mytableP {border:none;width:100%;color:#666;margin:0;padding:0;}
      .mytableP th {font:bold 11px Calibri,Cambria,Verdana, Arial;color:#FFFFFF;border-right:1px solid #C1DAD7;border-bottom:1px solid #C1DAD7;border-top:1px solid #C1DAD7;letter-spacing:1px;text-transform:uppercase;text-align:left;background:#99CC33 repeat;padding:2px 2px 2px 3px;}
      .mytableP td {border-right:1px solid #CCC;border-bottom:1px solid #CCC;border-top:1px solid #CCC;border-left:1px solid #CCC;font:12px Calibri,Cambria,Verdana, Arial;color:#333;padding:2px 2px 2px 3px;}
  7. For showing Export to Excel icon in right bottom of the page.
    • .e2e { position:fixed; bottom:0; right:0;}
For Export to Excel File please check source file and read comments inside. This tutorial is based on phpeasystep tutorial which is written using mysql_query (deprecated function). I used PDO (PHP Data Objects ) and also provide export to excel option for this along with table style. For More Tutorials please visit http://crewow.com/