Tuesday, 21 June 2016

PHP-MYSQLI Framework/Library For PHP application Development


A lot of Frameworks are available in PHP like cakephp,laravel,symfony,wordpress,joomla,drupal.etc. But all of them have their own restrictions, you cannot query it like what u want. Because they have their own canvas & u have to study their canvas structure to actually develop something in it. But for small application & websites you do not want to  use advanced heavy frameworks. For these type of small projects, you can use corephp frameworks.

By considering this, I have developed a  PHP-MYSQLI object oreiented  framework. Here You can query as you want, If you dont want to query also, Just use framworks methods, it is very simple...

Just Download framework from here...

Download From Here: https://github.com/litto/PHP-MYSQLI-Framework.git

The Project has 3 main Folders named- core,models,lib.
In core folder  MYSQLI & DB object Library class is situated... Here You dont want to change anything... This is the actual  core of our framework...
Next is  Models folder, It is actually files describing about the tables & their fields... In it we can describe how many fields the table has, that table has any relation with other tables.etc...
Include mysqlidb and dbObject classes. If you want to use model autoloading instead of manually including them in the scripts use autoload() method.

require_once("libs/MysqliDb.php");
require_once("libs/dbObject.php");

// db instance
$db = new Mysqlidb('localhost', 'user', '', 'testdb');
// enable class autoloading
dbObject::autoload("models");
Each database table could be easily mapped into a dbObject instance. If you do not want to create model for a simple table its object could be simply created with a table() method.

$user = dbObject::table("users");
Otherwise basic model should be declared as:

class user extends dbObject {}
In case autoload is set to 'models' directory, the filename should be models/user.php

Class will be related to 'user' table. To change the table name, define correct name in the $dbTable variable:

    protected $dbTable = "users";
Both objects created throw new class file creation of with table() method will have the same set of methods available. Only exception is that relations, validation or custom model methods will not be working with an objects created with table() method.

Third folder is lib folder.. In it you can create classes, but make sure that its name should not be same as any model names placed in model directory.. The benefit of creating files in it is that, you can write simple query's you want instead of using frameworks default functions..

Then in the rootfolder you can see a file named config, in this file only we are  describing the connection parameters named database name,username,password.etc...

Please download the files from above & just install it & see the structure . I have created list file, Create file, Edit file, delete file.etc., Database can be seen in db folder. Just import in your sql database & see its working or not?. So you can easily remember the structure... If you have any doubt please contact me....

Sunday, 7 February 2016

Installing PHP Pear Packages & Mail in Linux

In Linux we can setup Pear Packages & can directly send mail via SMTP & IMAP protocols.
First I will explain how to install Pear Packages in Linux.
Open Terminal, then type the following lines;-

sudo apt-get install php-pear
sudo pear install mail
sudo pear install Net_SMTP
sudo pear install Auth_SASL
sudo pear install mail_mime

Actually this will only download the required packages & store in a folder. So we have to execute it by typing the code below.

sudo gunzip /build/php5-0LI9sl/php5-5.5.9+dfsg/pear-build-download/*.tar
sudo pear upgrade /build/php5-0LI9sl/php5-5.5.9+dfsg/pear-build-download/*.tar

Here Location will be different for different installation, so you just replace the location depend on your installation
Now just restart the apache server
sudo service apache2 restart

Next step is to install Imap package.Type below in the terminal
sudo apt-get install php5-imap
sudo php5enmod imap
sudo service apache2 restart

Now check..everything will work Perfectly..

Changing The root mysql Password in Linux

Unlike windows, In linux its mandatory to give Mysql root password,otherwise it will not allow us to enter into the database. I will explain step by step on how to do this.

1) Stop the running Mysql process. It by typing following command in the Terminal.
sudo /etc/init.d/mysql stop

2)Connect to Mysql server without password. For this type the following in the terminal.
sudo mysqld_safe --skip-grant-tables &

3)Connect to mysql user using mysql client

sudo mysql -u root

4) Now you will enter into mysql inter face, type following in the terminal
use mysql;
update user set password=PASSWORD("NEW-ROOT-PASSWORD") where user='root';
flush privilages;
quit

5) stop Mysql server

sudo /etc/init.d/mysql stop


6) Now start the Mysql server and test it
sudo /etc/init.d/mysql start
mysql -u root -p

Setting up PHP Mysql in Linux

We are familiar with WAMP in windows for running PHP applications. Like wise it is Known as LAMP in Linux. LAMP stands for Linux Apache Mysql PHP

Below I will show step by step  instruction on how to install it.

1) First step is we have to install Apache. For this :-
Open Terminal(Applications->Accessories->Terminal)

sudo apt-get install apache2

Then it will ask you for password & type enter.

2) Test whether it is installed correctly or not. For this type http://localhost in the browser url. It will give a page if its correctly installed.

3) Next step is to install PHP. For this type the following in the Terminal & press enter

sudo apt-get install php5 libapache2-mod-php5

4) Now restart apache to make php compatible with apache. Type the following in terminal & press enter

sudo /etc/init.d/apache2 restart

5) Next step is to install Mysql. For this Type following in the terminal & press enter
sudo apt-get install mysql-server


6) Next step is to instal;l PHPmyadmin, which is an easy tool to edit our databases. For this type the following in terminal & press enter
sudo apt-get install libapache2-mod-auth-mysql  php5-mysql  phpmyadmin

7) Next step is to make mysql work with PHP , for this we have to open PHP configuration file and enable mysql extension in it.
gksudo gedit /etc/php5/apache2/php.ini

Find the Line
;extension=mysql.so   
Remove the semicolon which will look like this
extension =mysql.so

8) Now Just restart the apache
sudo /etc/init.d/apache2 restart

9) Now check if its working by typing localhost/phpmyadmin in your browser. if its giving error then
we have to edit apache2.config file .Type following Line & press enter
sudo gedit /etc/apache2/apache2.conf

Include the following line in the bottom of the page..

Include /etc/phpmyadmin/apache.conf


10) Now Just restart apache & check..

sudo /etc/init.d/apache2 restart

To find out strict mode status, run the below sql

SHOW VARIABLES LIKE 'sql_mode';

If the output value contains STRICT_TRANS_TABLES, then strict mode is enabled.

To disable strict mode, run the below sql

SET GLOBAL sql_mode = '';

To enable strict mode, run the below sql

SET GLOBAL sql_mode = 'STRICT_TRANS_TABLES';

 


Now Everything will be working fine... Enjoy...



Installing Symfony in Windows

Symfony-The leading PHP framework to create websites and web applications. Built on top of the Symfony Components. Installation of symfony is slightly different from PHP's other frameworks. I will explain you step by step on how to set up your first Symfony application running in your windows PC.
1) Firstly make sure that curl is installed in your computer. If not then download it from here
Then Extract the folder & copy all the contents & paste it into the C:/Windows/System32 Folder.

2) Now its time to install Symfony. First open the Command prompt (type run insearch.,In it type cmd & press enter). Open it in administrator mode.

3) In the command prompt window just type
php -r "readfile('https://symfony.com/installer');" > symfony

2) Now symfony installation file will be automatically downloaded into your system.Now its time to move the downloded file to the working folder. For this type in the cmd like shown below , second argument will be location of the project. After that enter into the directory By typing cd & then executing PHP command.

3) Now its time to create the application. Now enter into the directory type the following command
php new my_project

4) To run the application, Enter into the project folder from cmd & then type
php app/console server:run
5) The  inorder to view our application go to the browser & type
localhost:8000/
6) To stop the application run,type following in the cmd
php app/console server;stop


c:\> move symfony c:\wamp\www\myapps\
c:\> cd wamp
c:\wamp> cd www
c:\wamp\www>cd myapps
c:\wamp\www\myapps\> php symfony  
c:\wamp\www\myapps\> php new my_project_name   /* project will be created*/
c:\wamp\www\myapps\> cd my_project_name        /*Navigate to project Directory */    
c:\wamp\www\myapps\my_project_name\> php app/console server:run  /* Running the application */

Thursday, 13 August 2015

Solution for WampServer doesn't start on Windows 10

In windows 10 wampserver has some problem in starting its services. Normally if you try to type localhost in the server it will not show anything. Also the W icon for wamp server will be shown inactive or Yellow colour.
 The problem is that in Windows 10 IIS service is automatically installed with the OS. So the port number 80 which the Wampserver is using is reserved by Windows IIS. So wampserver will not start.

Solution

1) Click on the wamp tray icon on the left
2) Click on Apache->
3)Click on httpd.conf file
4) Inside it their is a line like


#Listen 12.34.56.78:80

Listen 80

Replace it with these lines :-


#Listen 12.34.56.78:80

Listen 8080


5)Look for another line  like:-

ServerName localhost:80

6) Replace it with

ServerName localhost:8080

7)Now Restart all services, You can notice that wamp icon is changes to green.

8) Now go to browser and visit localhost:8080/ 
default wamp page will open.

9) But for accessing Phpmyadmin database, if we go to localhost:8080/phpmyadmin/ it will not work. It will show forbidden access.

10) Navigate to wamp/ alias/ and open phpmyadmin.conf file.

11) Replace these lines 

Order Deny,Allow
Deny from all

Allow from 127.0.0.1

with

 Order Deny,Allow 

    Allow from all

11)  Now navigate to localhost:8080/phpmyadmin/
it will work fine.


Wednesday, 29 July 2015

Creating your own mail application in PHP

First time when you read the title of this post, You will get surprised. But believe me its very simple in PHP. For that purpose there is a library in php known as IMAP.

Connection to IMAP

To establish a connection to the IMAP server, we use the imap_connect() function as shown here:
<?php
$imap = imap_open($mailboxPath, $username, $password);
?>

The mailbox path, username, and password strings are required parameters to connect to the server. You can learn about the optional parameters in the manual.

The mailbox path is a string that identifies server and port information in braces followed by the name of the desired mail folder. Here are a few strings for the inbox folder for popular mail providers:

Gmail {imap.gmail.com:993/imap/ssl}INBOX
Yahoo {imap.mail.yahoo.com:993/imap/ssl}INBOX
AOL {imap.aol.com:993/imap/ssl}INBOX

Some servers do not have SSL enabled, in which case you would omit “SSL” from the string. Other servers might use self-signed certificates, in which you would include “novalidate-cert”.

<?php
$imap = imap_open("{localhost:993/imap/ssl/novalidate-cert}", "username", "password");
?>

Listing the Folders

Inbox, sent, trash, and spam folders are seen in pretty much every email account, and users can often create custom folders as well. In order to view messages in these folders, we need to change our connection string. For example, I used “INBOX” in the path string earlier. If I wanted to connect to the spam folder, I might want to use something like “Spam” instead. But even though it might be listed as Spam in your email account when viewed through a mail client, the real folder name might be different behind the scenes. We can list all of the available folders in an account using imap_list().

<?php
$folders = imap_list($imap, "{imap.gmail.com:993/imap/ssl}", "*");
echo "<ul>";
foreach ($folders as $folder) {
    $folder = str_replace("{imap.gmail.com:993/imap/ssl}", "", imap_utf7_decode($folder));
    echo '<li><a href="mail.php?folder=' . $folder . '&func=view">' . $folder . '</a></li>';
}
echo "</ul>";
?>
We have to pass the connection handle obtained with imap_open() as the initial parameter to imap_list(). We also need to pass a bare path sting (without the folder, e.g. “INBOX”). The star as the third parameter requests all of the available folders.

Mail Script(mail.php)

Just paste the code I will explain one by one...

<?php

//Here receiving all values here so that will use in all functions

$func = (!empty($_GET["func"])) ? $_GET["func"] : "view";
$folder = (!empty($_GET["folder"])) ? $_GET["folder"] : "INBOX";
$uid = (!empty($_GET["uid"])) ? $_GET["uid"] : 0;
$no=(!empty($_GET["no"])) ? $_GET["no"] : 0;
$part=(!empty($_GET["part"])) ? $_GET["part"] : 0;
$enc=(!empty($_GET["enc"])) ? $_GET["enc"] : 0;
$path='';

//username and password of mail. In the server name portion just paste your server name. if you want to fetch google mail you have to get SSL certified server. 

$username = 'usernamehere';
$password = 'passwordhere';
$imap = imap_open("{servername:143/novalidate-cert}".$folder,$username,$password);

// Checking which is the called function 

switch ($func) {
    case "delete":
        deleteMail($imap, $folder, $uid);
        break;

    case "read":
        readMail($imap, $folder, $uid,$no);
        break;

     case "download":
     downloadAttachment($imap, $uid, $part, $enc, $path);  

    case "view":
    default:
        viewMail($imap, $folder);
        break;

       
}

// function to read all mails in corresponding folder. If the folder is inbox it will list all emails in the Inbox folder.

function viewMail($imap, $folder){


     $numMessages = imap_num_msg($imap);
    $k=0;
for ($i = 0; $i <= $numMessages; $i++) {
  
  if($numMessages>$k){
    $header = imap_header($imap, $i);
if(isset($header->from[0])){
    $fromInfo = $header->from[0];
}
if(isset($header->reply_to[0])){
    $replyInfo = $header->reply_to[0];
}
    $details = array(
        "fromAddr" => (isset($fromInfo->mailbox) && isset($fromInfo->host))
            ? $fromInfo->mailbox . "@" . $fromInfo->host : "",
        "fromName" => (isset($fromInfo->personal))
            ? $fromInfo->personal : "",
        "replyAddr" => (isset($replyInfo->mailbox) && isset($replyInfo->host))
            ? $replyInfo->mailbox . "@" . $replyInfo->host : "",
        "replyName" => (isset($replyTo->personal))
            ? $replyto->personal : "",
        "subject" => (isset($header->subject))
            ? $header->subject : "",
        "udate" => (isset($header->udate))
            ? $header->udate : ""
    );

    $uid = imap_uid($imap, $i);

    echo "<ul>";
    echo "<li><strong>From:</strong>" . $details["fromName"];
    echo " " . $details["fromAddr"] . "</li>";
    echo "<li><strong>Subject:</strong> " . $details["subject"] . "</li>";
    echo '<li><a href="mail.php?folder=' . $folder . '&uid=' . $uid . '&func=read&no='.$i.'">Read</a>';
    echo " | ";
    echo '<a href="mail.php?folder=' . $folder . '&uid=' . $uid . '&func=delete">Delete</a></li>';
    echo "</ul>";
$k++;
}
}
}

//This will delete the correspond mail with UID

function deleteMail($imap, $folder, $uid){

    imap_delete($imap, $uid, FT_UID);
imap_expunge($imap);
}

//This function will read corresponding mail.it will display the mail content and fetch the attachment also

function readMail($imap, $folder, $uid,$no){
$func='download';
    echo $gh=getBody($uid,$imap);
       $mailStruct = imap_fetchstructure($imap, $no);
       print_r($mailStruct);
$attachments = getAttachments($imap, $no, $mailStruct, "");
//print_r($attachments);

echo "Attachments: ";
foreach ($attachments as $attachment) {

echo '<a href="mail.php?func=' . $func . '&folder=' . $folder . '&uid=' . $uid .
    '&part=' . $attachment["partNum"] . '&enc=' . $attachment["enc"] . '">' .
    $attachment["name"] . "</a>";
}
}

//This function is called inside read mail. Here it will read the attachment details of the mail. if nothing is their will send null

function getAttachments($imap, $mailNum, $part, $partNum) {
    $attachments = array();

    if (isset($part->parts)) {
        foreach ($part->parts as $key => $subpart) {
            if($partNum != "") {
                $newPartNum = $partNum . "." . ($key + 1);
            }
            else {
                $newPartNum = ($key+1);
            }
            $result = getAttachments($imap, $mailNum, $subpart,
                $newPartNum);
            if (count($result) != 0) {
                 array_push($attachments, $result);
             }
        }
    }
    else if (isset($part->disposition)) {
        if ($part->disposition == "attachment") {
            $partStruct = imap_bodystruct($imap, $mailNum,
                $partNum);
            $attachmentDetails = array(
                "name"    => $part->dparameters[0]->value,
                "partNum" => $partNum,
                "enc"     => $partStruct->encoding
            );
            return $attachmentDetails;
        }
    }

    return $attachments;
}

//This function is used to download attachments from the mail.It is called in read mail function

function downloadAttachment($imap, $uid, $partNum, $encoding, $path) {
    $partStruct = imap_bodystruct($imap, imap_msgno($imap, $uid), $partNum);

    $filename = $partStruct->dparameters[0]->value;
    $message = imap_fetchbody($imap, $uid, $partNum, FT_UID);

    switch ($encoding) {
        case 0:
        case 1:
            $message = imap_8bit($message);
            break;
        case 2:
            $message = imap_binary($message);
            break;
        case 3:
            $message = imap_base64($message);
            break;
        case 4:
            $message = quoted_printable_decode($message);
            break;
    }

    header("Content-Description: File Transfer");
    header("Content-Type: application/octet-stream");
    header("Content-Disposition: attachment; filename=" . $filename);
    header("Content-Transfer-Encoding: binary");
    header("Expires: 0");
    header("Cache-Control: must-revalidate");
    header("Pragma: public");
    echo $message;
}

//Function used to get details of body part in the mail


function getBody($uid, $imap) {
    $body = get_part($imap, $uid, "TEXT/HTML");
    // if HTML body is empty, try getting text body
    if ($body == "") {
        $body = get_part($imap, $uid, "TEXT/PLAIN");
    }
    return $body;
}

function get_part($imap, $uid, $mimetype, $structure = false, $partNumber = false) {
    if (!$structure) {
           $structure = imap_fetchstructure($imap, $uid, FT_UID);
    }
    if ($structure) {
        if ($mimetype == get_mime_type($structure)) {
            if (!$partNumber) {
                $partNumber = 1;
            }
            $text = imap_fetchbody($imap, $uid, $partNumber, FT_UID);
            switch ($structure->encoding) {
                case 3: return imap_base64($text);
                case 4: return imap_qprint($text);
                default: return $text;
           }
       }

        // multipart 
        if ($structure->type == 1) {
            foreach ($structure->parts as $index => $subStruct) {
                $prefix = "";
                if ($partNumber) {
                    $prefix = $partNumber . ".";
                }
                $data = get_part($imap, $uid, $mimetype, $subStruct, $prefix . ($index + 1));
                if ($data) {
                    return $data;
                }
            }
        }
    }


    return false;
}
//Function will identify the mime type of the mail

function get_mime_type($structure) {
    $primaryMimetype = array("TEXT", "MULTIPART", "MESSAGE", "APPLICATION", "AUDIO", "IMAGE", "VIDEO", "OTHER");

    if ($structure->subtype) {
       return $primaryMimetype[(int)$structure->type] . "/" . $structure->subtype;
    }
    return "TEXT/PLAIN";
}

?>


Saturday, 18 October 2014

Simple Library Functions to use MYSQLi in your PHP Project

For every projects developed in PHP the database used by most of the users are MYSQL. But developers have a bad news because Mysql queries are being depreciated by the latest versions of PHP. So We have to migrate our existing PHP Mysql projects to Mysqli or PDO.
I have explained with library functions how to migrate MYSQL to PDO in the previous post. In this post I will give you a library which can be used for Mysqli projects. You Just need to replace this library file in your lib folder if you are using the conventional library file that I have explained in one of my previous posts.


For this we have to create a config.php file in the root folder giving the connection details.It will look like this:-

<?php


$config["databaseHost"] = "hostname";
$config["databaseUser"] = "username";
$config["databasePass"] = "password";
$config["databaseName"]= "databasename";

?>

So here you go. I will give you MYSQL lib file , just copy & paste in the lib file Mysql & everything will works fine....

<?php

class MySql
{

private $dbUser;
private $dbPass;
private $dbName;
private $dbHost;
private $dbConnection;
private $errorString;
private $filter;
private $util;
public static $instance;
public $query;
public $newCon;


function __construct(){

$this->dbConnection = null;
$this->filter = true;
$this->newCon = false;
}


function setNew(){
$this->newCon = true;
}
function noFilter()
{
$this->filter = false;
}
/*
* Setting Error Message on Db Operation
* Input String Message
* Called upon db operation
*/

function setError($string)
{
$this->errorString = $string;
//echo "MYSQL ERROR - ".$this->errorString;
}

/*
* get Error Message after a db operation
* Retrieves the current error Status
*/

function getError()
{
return $this->errorString;
}

/*
* Connect to Mysql Database using set up data
* Set up data being hold on Constructor
* Modify the constrct params for connection change
*/

function connect()
{
if(is_null($dbConnection)){
                require_once(CONST_BASEDIR.'/config.php') ;
$this->dbUser = $config["databaseUser"];
$this->dbPass = $config["databasePass"];
$this->dbName = $config["databaseName"];
$this->dbHost = $config["databaseHost"];

$dbConnection = new mysqli($this->dbHost,$this->dbUser,$this->dbPass,$this->dbName);
if($this->dbConnection->connect_error) {
echo 'Connection Error'.$conn->connect_error;
}
}
}

function getInstance(){
return $this->dbConnection;
}


function close()
{
if($this->dbConnection){
$this->dbConnection->close();

$this->dbConnection = null;
}else{
$this->dbConnection = null;
}
}


function fetchAll($query)
{
           include(CONST_BASEDIR.'/config.php') ;
$this->dbUser = $config["databaseUser"];
$this->dbPass = $config["databasePass"];
$this->dbName = $config["databaseName"];
$this->dbHost = $config["databaseHost"];

$dbConnection = new mysqli($this->dbHost,$this->dbUser,$this->dbPass,$this->dbName);
$fileds = array();
$resultSet = array();
$result=$dbConnection->query($query);
$arr = $result->fetch_all(MYSQLI_ASSOC);
return $arr;
}


function insert($options,$table)
{
include(CONST_BASEDIR.'/config.php') ;
$this->dbUser = $config["databaseUser"];
$this->dbPass = $config["databasePass"];
$this->dbName = $config["databaseName"];
$this->dbHost = $config["databaseHost"];

         $dbConnection = new mysqli($this->dbHost,$this->dbUser,$this->dbPass,$this->dbName);
$queryString = "";
$p = count($options);
$start = 0;
$fieldString = null;
$valueString = null;
foreach($options as $key=>$val){
$fieldString.=" `{$key}`";
$vk=$dbConnection->real_escape_string($val);
$valueString.=" '{$vk}' ";
if($start<$p-1){
$fieldString.=",";
$valueString.=",";
}
$start++;
}
$queryString = "INSERT INTO `{$table}` ({$fieldString}) VALUES ({$valueString}) ";

//echo "db".$queryString;

//$result = mysql_query($queryString) or $this->setError("Insert".mysql_error());

   $result = $dbConnection->query($queryString);
   //$last_inserted_id = $dbConnection->insert_id;

}

function update($options,$table,$condition)
{
include(CONST_BASEDIR.'/config.php') ;
$this->dbUser = $config["databaseUser"];
$this->dbPass = $config["databasePass"];
$this->dbName = $config["databaseName"];
$this->dbHost = $config["databaseHost"];

         $dbConnection = new mysqli($this->dbHost,$this->dbUser,$this->dbPass,$this->dbName);

$queryString = "";
$fieldString = "";
$p = count($options);
$start = 0;
foreach($options as $key=>$val){
$vk=$dbConnection->real_escape_string($val);
            $fieldString.=" `{$key}`='{$vk}'";
if($start<$p-1){
$fieldString.=",";
}
$start++;
}
$queryString = "UPDATE `{$table}` SET {$fieldString} ";
if(!empty($condition)){
$queryString.=" WHERE {$condition} ";
}
$this->query = $queryString;
$result = $dbConnection->query($queryString);


}


function delete($table,$condition)
{
include(CONST_BASEDIR.'/config.php') ;
$this->dbUser = $config["databaseUser"];
$this->dbPass = $config["databasePass"];
$this->dbName = $config["databaseName"];
$this->dbHost = $config["databaseHost"];

         $dbConnection = new mysqli($this->dbHost,$this->dbUser,$this->dbPass,$this->dbName);
$queryString = "DELETE FROM `{$table}` ";
if(!empty($condition)){
$queryString.=" WHERE {$condition} ";
}
$result = $dbConnection->query($queryString);
      return true;

}


function execute($query){
include(CONST_BASEDIR.'/config.php') ;
$this->dbUser = $config["databaseUser"];
$this->dbPass = $config["databasePass"];
$this->dbName = $config["databaseName"];
$this->dbHost = $config["databaseHost"];
   $dbConnection = new mysqli($this->dbHost,$this->dbUser,$this->dbPass,$this->dbName);
                $result = $dbConnection->query($queryString);


}

function addFilter($string){
return addslashes($string);

}

function removeFilter($string){
return stripslashes($string);
}


function escapeHtml($text){
return strip_tags($text);
}





}
?>

Now I will explain how to use it. This Mysql.php will be your main library file. 
So after this for your projects you want to write classes for each section like User section, company section.etc. 
so you create classes like Company.php, User.php .etc..

So Inorder to implement functions from parent class you have to declare classes like

<?php

class Company extends MySql{
}

?>



Now i will  explain how it is used:-
@for deleting arecord you have to just call like this
for eg:-
$this->delete('cms_company','`company_id`='.$list[$i]);
@for updating a record you have to just call like this
for eg:
$this->update(array('status'=>'0'),"cms_company",'`company_id`='.$list[$i]);
@for fetching data ,you have to call like this.
for eg:
$query = "SELECT count(c.`company_id`) FROM `cms_company` c WHERE c.`company_id`!=''";
$query.=$qry;
$rec = $this->fetchAll($query);

@for inserting data you have to only do like this
for eg:
$insert = array('company_name'=>$txtTitle,'company_logo'=>$file,'company_banner'=>$file1,'company_address'=>$txtContent,'company_desc'=>$txtdesc,'company_web'=>$web);// array of values in table

$this->insert($insert,'cms_company');





Friday, 17 October 2014

Simple Library Functions to use PDO in Your Project

Now Everyone knows that mysql queries are in the way of depreciation. They are no longer supported by the mysql project team. Main reason is because of the lack of improved security features in mysql query executions. So many of the mysql query execution are in the threat od phishing attacks. So here am providing a basic library of using PDO who wants to change their existing MYSQL projects directly to PDO  by only changing one library file.

For this we have to create a config.php file in the root folder giving the connection details.It will look like this:-

<?php


$config["databaseHost"] = "hostname";
$config["databaseUser"] = "username";
$config["databasePass"] = "password";
$config["databaseName"]= "databasename";

?>

So After that Include Mysql.php file as I explained in my post check here


So the changed Mysql file for PDO will be:-

<?php

class MySql
{
/*
 * Date:8-16-2014
 * Login Form , entry to the application
 * Auhthor : Litto chacko
 * Email:littochackomp@gmail.com
*/
public $dbUser;
public $dbPass;
public $dbName;
public $dbHost;
private $dbConnection;
private $errorString;
private $filter;
private $util;
public static $instance;
public $query;
public $newCon;

function __construct(){

$dbConnection = null;
$this->filter = true;
$this->newCon = false;

}


function setNew(){
$this->newCon = true;
}
function noFilter()
{
$this->filter = false;
}
/*
* Setting Error Message on Db Operation
* Input String Message
* Called upon db operation
*/

function setError($string)
{
$this->errorString = $string;
//echo "MYSQL ERROR - ".$this->errorString;
}

/*
* get Error Message after a db operation
* Retrieves the current error Status
*/

function getError()
{
return $this->errorString;
}

function connect()
{
if(is_null($dbConnection)){

                require_once(CONST_BASEDIR.'/config.php') ;
$this->dbUser = $config["databaseUser"];
$this->dbPass = $config["databasePass"];
$this->dbName = $config["databaseName"];
$this->dbHost = $config["databaseHost"];
try {

$dbConnection= new PDO('mysql:host='.$this->dbHost.';dbname='.$this->dbName.';charset=utf8', $this->dbUser, $this->dbPass,array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
return $dbConnection;
} catch(PDOException $ex) {
    print "Error!: " . $ex->getMessage() . "<br/>";
    //some_logging_function($ex->getMessage());
}
}
}

function getInstance(){
return $dbConnection;
}

/*
* Close the Mysql Connection  
*/
function addFilter($string){
return addslashes($string);

}

/*
* Remove added special chars on STring 
*/

function removeFilter($string){
return stripslashes($string);
}


function escapeHtml($text){
return strip_tags($text);
}



function close()
{
if($dbConnection){
$dbConnection = null;
}else{
$dbConnection = null;
}
}

function fetchAll($query)
{

include(CONST_BASEDIR.'/config.php') ;
$dbUser = $config["databaseUser"];
$dbPass = $config["databasePass"];
$dbName = $config["databaseName"];
$dbHost = $config["databaseHost"];
try {

$db= new PDO('mysql:host='.$dbHost.';dbname='.$dbName.';charset=utf8', $dbUser, $dbPass,array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$fileds = array();
        $resultSet = array();
   $stmt = $db->query($query);
   $result= $stmt->fetchAll(PDO::FETCH_ASSOC);
return $result;
} catch(PDOException $ex) {
    print "Error!: " . $ex->getMessage() . "<br/>";
    //some_logging_function($ex->getMessage());
}



}


function insert($options,$table)
{
$queryString = "";
$p = count($options);
$start = 0;
$fieldString = null;
$valueString = array();
include(CONST_BASEDIR.'/config.php') ;
$dbUser = $config["databaseUser"];
$dbPass = $config["databasePass"];
$dbName = $config["databaseName"];
$dbHost = $config["databaseHost"];
try {

$db= new PDO('mysql:host='.$dbHost.';dbname='.$dbName.';charset=utf8', $dbUser, $dbPass,array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
foreach($options as $key=>$val){
$fieldString.=" `{$key}`";
$valueString[":".$key.""]="{$val}";
$vs.=":".$key;
if($start<$p-1){
$fieldString.=",";
$vs.=",";
}
$start++;
}

//$dc=$valueString;
$queryString = "INSERT INTO `{$table}` ({$fieldString}) VALUES ({$vs}) ";
$stmt = $db->prepare($queryString);
$stmt->execute($valueString);
 //$affected_rows = $stmt->rowCount();

} catch(PDOException $ex) {
    print "Error!: " . $ex->getMessage() . "<br/>";
    //some_logging_function($ex->getMessage());
}


}



function update($options,$table,$condition)
{
$queryString = "";
$fieldString = "";
   $valueString = array();
$p = count($options);
$start = 0;

include(CONST_BASEDIR.'/config.php') ;
$dbUser = $config["databaseUser"];
$dbPass = $config["databasePass"];
$dbName = $config["databaseName"];
$dbHost = $config["databaseHost"];
try {

$db= new PDO('mysql:host='.$dbHost.';dbname='.$dbName.';charset=utf8', $dbUser, $dbPass,array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
foreach($options as $key=>$val){
$vs=":".$key;
$fieldString.=" `{$key}`={$vs}";
$valueString[":".$key.""]="{$val}";

if($start<$p-1){
$fieldString.=",";
}
$start++;
}
$queryString = "UPDATE `{$table}` SET {$fieldString} ";
if(!empty($condition)){
echo $queryString.=" WHERE {$condition} ";
}

$stmt = $db->prepare($queryString);
$stmt->execute($valueString);
} catch(PDOException $ex) {
    print "Error!: " . $ex->getMessage() . "<br/>";
    //some_logging_function($ex->getMessage());
}


}


function delete($table,$condition)
{

include(CONST_BASEDIR.'/config.php') ;
$dbUser = $config["databaseUser"];
$dbPass = $config["databasePass"];
$dbName = $config["databaseName"];
$dbHost = $config["databaseHost"];
try {

$db= new PDO('mysql:host='.$dbHost.';dbname='.$dbName.';charset=utf8', $dbUser, $dbPass,array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

$queryString = "DELETE FROM `{$table}` ";
if(!empty($condition)){
$queryString.=" WHERE {$condition} ";
}
$result = $db->exec($queryString);
} catch(PDOException $ex) {
    print "Error!: " . $ex->getMessage() . "<br/>";
    //some_logging_function($ex->getMessage());
}


function execute($query){
   include(CONST_BASEDIR.'/config.php') ;
$dbUser = $config["databaseUser"];
$dbPass = $config["databasePass"];
$dbName = $config["databaseName"];
$dbHost = $config["databaseHost"];
try {

$db= new PDO('mysql:host='.$dbHost.';dbname='.$dbName.';charset=utf8', $dbUser, $dbPass,array(PDO::ATTR_EMULATE_PREPARES => false,PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));

$result = $db->exec($query);
} catch(PDOException $ex) {
    print "Error!: " . $ex->getMessage() . "<br/>";
    //some_logging_function($ex->getMessage());
}
}
}

?>
Now I will explain how to use it. This Mysql.php will be your main library file. 
So after this for your projects you want to write classes for each section like User section, company section.etc. 
so you create classes like Company.php, User.php .etc..

So Inorder to implement functions from parent class you have to declare classes like

<?php

class Company extends MySql{
}

?>
@for deleting arecord you have to just call like this
for eg:-
$this->delete('cms_company','`company_id`='.$list[$i]);
@for updating a record you have to just call like this
for eg:
$this->update(array('status'=>'0'),"cms_company",'`company_id`='.$list[$i]);
@for fetching data ,you have to call like this.
for eg:
$query = "SELECT count(c.`company_id`) FROM `cms_company` c WHERE c.`company_id`!=''";
$query.=$qry;
$rec = $this->fetchAll($query);

@for inserting data you have to only do like this
for eg:
$insert = array('company_name'=>$txtTitle,'company_logo'=>$file,'company_banner'=>$file1,'company_address'=>$txtContent,'company_desc'=>$txtdesc,'company_web'=>$web);// array of values in table

$this->insert($insert,'cms_company');