DevSael Blog. C, CPP, C++, PHP, .NET Programming BLOG! advanced, MySQL, MongoDB, RDBMS.

Browsing "Older Posts"

PHP Mongodb Indexing:
It is not so hard to make index in Bigdata database such like MongoDB. Take look following bellow.

<?php

$c = new MongoCollection($db, 'foo');

// Create an index on 'A' ascending
$AscIndex = array('A' => 1);
$c->createIndex($AscIndex);

// Create an index on 'A' descending
$DscIndex = array('A' => -1);
$c->createIndex($DscIndex);

// Create a unique index on 'a_row_index'
$a_row_index = array('a_row_index' => 1), array('unique' => true);
$cIndex -> createIndex($a_row_index);

// create a compound index on 'XY' ascending and 'YX' descending
$XyYx = array('XY' => 1, 'YX' => -1);
$cIndex -> createIndex($XyYx);

?>

MongoDB indexing in PHP

By Game Changer → Thursday, February 25, 2016

PHP isset() equiv JavaScript isset() funciton:

Often I am get asked from junior developers that, Is there any isset() function in Javascript? Ha ha ha. I ignore them, but let them try to create a custom function to do this job.
Ok no more words...Let get it...
/**
 * 
 * @returns {Boolean}
 * Original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
 * Improved by: FremyCompany
 * Improved by: Onno Marsman
 * Improved by: Rafał Kukawski
 * Example-1: isset( undefined, true);
 * Returns: false
 * Example 2: isset( 'Kevin van Zonneveld' );
 * Returns: true
 */
function isset ()
{

  var a = arguments,
    l = a.length,
    i = 0,
    undef;

  if (l === 0)
  {
    throw new Error('Empty isset');
  }

  while (i !== l)
  {
    if (a[i] === undef || a[i] === null)
    {
      return false;
    }
    i++;
  }
  return true;
}
But........
The problem is this will raise an exception when calling isset(abc.def.ghi) in case if abc.defis undefined. However by combining this solution with the one that accepts a variable name in a form of a string, it will be identical to the PHP version

You can use this function as PHP isset() given to use.

var a;

a = {
    b: {
        c: 'e'
    }
};

function isset (obj, path) {
    var stone;

    path = path || '';

    if (path.indexOf('[') !== -1) {
        throw new Error('Unsupported object path notation.');
    }

    
    path = path.split('.');
    
    do {
        if (obj === undefined) {
            return false;
        }

        stone = path.shift();
        
        if (!obj.hasOwnProperty(stone)) {
            return false;
        }
        
        obj = obj[stone];
        
    } while (path.length);

    return true;
}

console.log(
    isset(a, 'b') == true,
    isset(a, 'b.c') == true,
    isset(a, 'b.c.d') == false,
    isset(a, 'b.c.d.e') == false,
    isset(a, 'b.c.d.e.f') == false
);

Another Way to do isset() function using javascript.

if(typeof(data.length) != 'undefined')
    {
       // do something
    }

    if(empty(data))
    {
        // do something
    }

   if(typeof(data) == 'undefined' || data === null)
   {
     //do something
   }

JavaScript isset() equivalent PHP isset()

By Game Changer → Thursday, December 17, 2015


From the terminal:
Hristo$ sudo /usr/local/mysql/support-files/mysql.server start
Starting MySQL
.....................................................................
ERROR! Manager of pid-file quit without updating file.
so I checked the status:
Hristo$ sudo /usr/local/mysql/support-files/mysql.server status
Password:
/usr/local/mysql/support-files/mysql.server: line 418: pidof: command not found
 ERROR! MySQL is not running
Again tried this?
Hristo$ /usr/local/mysql/bin/mysql -u root -p
Enter password: 
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

mysql.err:
100706 11:38:36 mysqld_safe Starting mysqld daemon with databases from /usr/local/mysql/data
100706 11:38:36 [Warning] '--log' is deprecated and will be removed in a future release. Please use ''--general_log'/'--general_log_file'' instead.
100706 11:38:36 [Warning] '--log_slow_queries' is deprecated and will be removed in a future release. Please use ''--slow_query_log'/'--slow_query_log_file'' instead.
100706 11:38:36 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/mysql/data/ is case insensitive
100706 11:38:36 [Note] Plugin 'FEDERATED' is disabled.
100706 11:38:36  InnoDB: Started; log sequence number 0 69987
100706 11:38:36 [ERROR] Can't start server : Bind on unix socket: Permission denied
100706 11:38:36 [ERROR] Do you already have another mysqld server running on socket: /var/mysql/mysql.sock ?
100706 11:38:36 [ERROR] Aborting

100706 11:38:36  InnoDB: Starting shutdown...
100706 11:38:41  InnoDB: Shutdown completed; log sequence number 0 69987
100706 11:38:41 [Note] /usr/local/mysql/bin/mysqld: Shutdown complete


Solution:

Configure correctly your my.cnf file.
[mysqld]
#
# * Basic Settings
#

user        = mysql
pid-file    = /var/run/mysqld/mysqld.pid
socket      = /var/run/mysqld/mysqld.sock
port        = 3306
basedir     = /usr
datadir     = /var/lib/mysql
tmpdir      = /tmp
skip-external-locking

#
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
bind-address        = 127.0.0.1

[Solved] MySQL Error on Snow Leopard

By Game Changer → Friday, December 11, 2015
PHP scripts to send the e-mail messages for contact form via SMTP. Already found several articles and PHPMailer tutorials? but a lot of them didn’t worked for you?

Why GMail for sending mail messages?

Obviously! it’s FREE! Sure most website owners can use their own SMTP server for sending email messages from their website, but it makes sense even than to use GMail for sending mail. The chance is big that your websites IP address is on a blacklist if your site is on hosted by a shared web hosting provider. If not or you host your site on your own server, there is always a risk that your IP address get blacklisted. Because of some limitations, the SMTP server from Google is a good choice applications with less than 500 recipients a day, check this information from the Google help pages.

Requirements

You need for this PHPMailer code example a PHP5 enabled web host (I did tests only on Linux), the port 465 need to be open and of course you need a GMail or Google Apps account.

Trouble sending e-mails with your “normal” GMail account? If you own a domain name, you can register for a Google Apps account or check below the tutorial update about an alternative SMTP service!

PHPMailer tutorial for GMail and Google Apps

Check that your web hosting provider has opened the port 465 (TCP out), if not ask him to open that port
Include the PHPMailer class file: require_once('phpmailer/class.phpmailer.php');
Create those two constant variables to store your GMail login and password. Use the login for your Google Apps mail account if you have one.
define('GUSER', 'you@gmail.com'); // GMail username
define('GPWD', 'password'); // GMail password
Use the following function to send the e-mail messages (add the function in one of your included files):
function smtpmailer($to, $from, $from_name, $subject, $body) { 
 global $error;
 $mail = new PHPMailer();  // create a new object
 $mail->IsSMTP(); // enable SMTP
 $mail->SMTPDebug = 0;  // debugging: 1 = errors and messages, 2 = messages only
 $mail->SMTPAuth = true;  // authentication enabled
 $mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for GMail
 $mail->Host = 'smtp.gmail.com';
 $mail->Port = 465; 
 $mail->Username = GUSER;  
 $mail->Password = GPWD;           
 $mail->SetFrom($from, $from_name);
 $mail->Subject = $subject;
 $mail->Body = $body;
 $mail->AddAddress($to);
 if(!$mail->Send()) {
  $error = 'Mail error: '.$mail->ErrorInfo; 
  return false;
 } else {
  $error = 'Message sent!';
  return true;
 }
}
Most of the settings inside the function are required by GMail. While searching for PHPmailer tutorials I found articles with different settings for the port and security. My advice is to use the settings from this tutorial. Call the function within your code:
smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!');
Use this more “advanced” usage inside your application:
if (smtpmailer('to@mail.com', 'from@mail.com', 'yourName', 'test mail message', 'Hello World!')) {
 // do something
}
if (!empty($error)) echo $error;
Advanced setup with fall-back SMTP server Because of the e-mail message limit it might be useful to use a secondary SMTP server if the GMail option is unable to send the message. For this functionality you need to replace the part with the SMTP settings. First create login/server variables for the second SMTP server:
define('SMTPUSER', 'you@yoursmtp.com'); // sec. smtp username
define('SMTPPWD', 'password'); // sec. password
define('SMTPSERVER', 'smtp.yoursmtp.com'); // sec. smtp server
Next we need to create an if/else statement using the variables for the second server (replace).
function smtpmailer($to, $from, $from_name, $subject, $body, $is_gmail = true) { 
 global $error;
 $mail = new PHPMailer();
 $mail->IsSMTP();
 $mail->SMTPAuth = true; 
 if ($is_gmail) {
  $mail->SMTPSecure = 'ssl'; 
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = 465;  
  $mail->Username = GUSER;  
  $mail->Password = GPWD;   
 } else {
  $mail->Host = SMTPSERVER;
  $mail->Username = SMTPUSER;  
  $mail->Password = SMTPPWD;
 }        
 $mail->SetFrom($from, $from_name);
 $mail->Subject = $subject;
 $mail->Body = $body;
 $mail->AddAddress($to);
 if(!$mail->Send()) {
  $error = 'Mail error: '.$mail->ErrorInfo;
  return false;
 } else {
  $error = 'Message sent!';
  return true;
 }
}
And next use the modified PHPMailer function as followed:
$msg = 'Hello World';
$subj = 'test mail message';
$to = 'to@mail.com';
$from = 'from@mail.com';
$name = 'yourName';
 
if (smtpmailer($to, $from, $name, $subj, $msg)) {
 echo 'Yippie, message send via Gmail';
} else {
 if (!smtpmailer($to, $from, $name, $subj, $msg, false)) {
  if (!empty($error)) echo $error;
 } else {
  echo 'Yep, the message is send (after doing some hard work)';
 }
}
Both examples are very simple and demonstrate only how-to send e-mail messages using PHPmailer with the SMTP server provided by GMail. Of course you can extend the code to handle HTML messages and attachments etc. If you have any issues with these examples, just let me know. UPDATE: Alternate SMTP service Since this tutorial was published, I got several messages that the free GMail account doesn’t allow you to send a lot of e-mail messages from your own websites. Your can use this PHPmailer example code for any other SMTP server or service. I suggest to use ElasticEmail, a premium e-mail service provider in the cloud. Signup for a free account which is good for the first 25.000 mail messages and 10.000 contacts every month. If you use the tutorial code with ElasticEmail you need to replace this part of code
 if ($is_gmail) {
  $mail->SMTPSecure = 'ssl'; 
  $mail->Host = 'smtp.gmail.com';
  $mail->Port = 465;  
  $mail->Username = GUSER;  
  $mail->Password = GPWD;   
 } else {
  $mail->Host = SMTPSERVER;
  $mail->Username = SMTPUSER;  
  $mail->Password = SMTPPWD;
 } 
with this code
 $mail->Host = 'smtp.elasticemail.com';
 $mail->Port = 2525; 
 $mail->Username = 'your username';
 $mail->Password = 'your password';
Optional: Remove the “$is_gmail” attribute from the function.
Tags:

Sending e-mails using SMTP with PHPMailer and GMail

By Game Changer →

Date and time manipulation is an unavoidable part of programming; there will inevitably be a part of a project that requires a date to be modified. While, on the surface, echoing a date in the future brings a small bit of accomplishment, it can be quickly eradicated when one is tasked with manipulating that date.
Without being aware of the arsenal of tools PHP provides you with regards to working with dates, you might find yourself writing kludges that convert strings into timestamps for various comparisons.
Today we’re going to dissect the PHP DateInterval class, a power tool for dealing with dates in a web app.
But before learning about the DateInterval object, one needs to first understand what an interval is.

What is an Interval?

Simply put, an interval is a duration of time.
When we converse about the topic of duration, we wouldn’t say, "Honey, I’ll be home on Dec 3rd, 2015 15:19pm".
Instead, we would simplify and say "I’ll be home in 5 minutes". Although this is ideal when conversing with another person, this is not so great as a data construct.
So how do we define "in 5 minutes" for a web app?
Fortunately, there’s an ISO for that.
ISO 8601 is the international standard that defines how to use, store, and transfer date, time, and duration information.
The specific string to define durations is an easy-to-remember pattern:
PYMDTHMS
  • P: period
  • Y: years
  • M: months
  • D: days
  • T: time
  • H: hours
  • M: minutes
  • S: seconds
Except for P, each designator is optional.
Immediately preceding each designator is the quantity of time you want to store.
Below is a table showing samples of different date and time ranges:
StringEquivalent to…
P1Y1 year
P1M1 month
P1D1 day
P30D30 days
PT1H1 hour
PT5M5 minutes
PT35S35 seconds
P1Y6M29DT4H34M23S1 year, 6 months, 29 days, 4 hours, 34 minutes, 23 seconds

Creating a DateInterval Object

Now that we understand what an interval is — it’s simply a duration of time — and that ISO 8601 defines our duration’s format, we can start playing around with the PHP DateInterval class.
Let’s define a predictable duration, create a DateInterval object, and output the result to the screen.
We’ll start with "1 year, 2 months, 3 days, 4 hours, 5 minutes, 6 seconds".
$Duration = new DateInterval( "P1Y2M3DT4H5M6S" );
print_r( $Duration );
Result:
DateInterval Object
(
[y] => 1
[m] => 2
[d] => 3
[h] => 4
[i] => 5
[s] => 6
...
)
You will notice that the constructor for the DateInterval class has parsed your duration and stored the individual values in its own properties. $Duration->ymatches the 1Y from the duration string you passed in.
Let’s try another more practical duration: 1 month. You’ll notice that any undefined durations are automatically defaulted to 0.
$Duration = new DateInterval( "P1M" );
print_r( $Duration );
Result:
DateInterval Object
(
[y] => 0
[m] => 1
[d] => 0
[h] => 0
[i] => 0
[s] => 0
...
)
So now we know what’s happening, but what do we really have? What’s so great and tangible about this?
The real benefit to what we have here is that the $Duration object itself represents a duration of time. We don’t need to know a source or destination date; $Duration is simply 1 month.
Note: It’s important to note that creating a DateInterval with 13 months (P13M) will not roll over and provide you with "1 year 1 month".
That makes sense because we don’t have a source or destination date. Imagine the case of 61 days:
  • On October 1, it’s 2 months
  • On December 1, it’s only 1 month and 30 days
  • On February 1, it’s 2 months and 2 days (or only 2 months and 1 day on leap years)

Manipulating Dates with Durations

Durations tame the manipulation of PHP DateTime objects.
The PHP DateTime class has three methods that work with a DateIntervalobject:
  • add
  • sub
  • diff
Both add and sub will modify a DateTime object by a DateInterval, while diffwill compare two DateTime objects and return a DateInterval.
$Now = new DateTime();
echo $Now->format('Y-m-d'); // 2014-06-12

$Duration = new DateInterval('P1M'); // 1 month
$Now->add( $Duration );
echo $Now->format('Y-m-d'); // 2014-07-12

$Duration = new DateInterval('P2M'); // 2 months
$Now->sub( $Duration );
echo $Now->format('Y-m-d'); // 2014-05-12
In the above example you can see how date manipulation becomes much easier and more predictable by using DateInterval objects to modify DateTime objects.
The diff method is just as easy to use, but provides an extra piece of information:total days. This is important because when using the DateTime object to find a difference, we have a source and destination date, and therefore we can reduce the units of time into larger denominations. However, having the total number of days in between is a valuable piece of information.
$Year = new DateInterval('P1Y');
echo $Year->days; // 0

$Date1 = new DateTime();
$Date2 = new DateTime();
$Date2->add( $Year );

$Difference = $Date1->diff( $Date2 );
echo $Difference->days; // 365

Reading Durations and Extracting Intervals

There are inevitably going to be times where you want to extract portions of the stored interval (much the same as you would a date).
The DateInterval class has a handy format method. PHP docs has a table for the format method that is a useful reference.
You use the format method like this:
$Duration = new DateInterval('P345D');
echo $Duration->format('I am %d days'); // I am 345 days
Note: It’s important to note, for those familiar with the strftime method, that the recognized characters are completely different. For example, theDateInterval::format method interprets %a as total days while strftimeinterprets it as a textual representation of the day (i.e. "Sun").
Oddly enough, DateInterval doesn’t natively have a way to extract the entire interval spec without the zero values. This leaves you with two options:
  1. Extract it with 0 elements, which is perfectly acceptable
  2. Extend the DateInterval class
The second option, extending the DateInterval class, brings upon it’s own difficulties that we won’t touch on here today.
To extract the interval spec with the 0 elements intact, you can use the same format method like so:
$Duration = new DateInterval('P345D');
echo $Duration->format('P%yY%mM%dDT%hH%iM%sS'); // P0Y0M345DT0H0M0S
If you want to confirm the above, simply create a new DateInterval with the result of the first:
$interval_spec = 'P345D';
$Duration1 = new DateInterval( $interval_spec );
echo $Duration1->format('%d'); // 345

$interval_spec = $Duration1->format('P%yY%mM%dDT%hH%iM%sS'); // P0Y0M345DT0H0M0S
$Duration2 = new DateInterval( $interval_spec );
echo $Duration2->format('%d'); // 345
You should now have a grasp on using the PHP DateInterval class, and it’s capabilities.
Hopefully you’re able to apply this current and future web app projects.

PHP DateInterval Class

By Game Changer →
We have two PHP5 objects and would like to merge the content of one into the second. There are no notion of subclasses between them so the solutions described in the following topic cannot apply.

Remarks:

  • Remember these are objects, not classes.
  • Objects will contain quite a lot of fields so a ``foreach`` would be quite slow.
  • So far we consider transforming objects A and B into arrays then merging them using array_merge() before re-transforming into an object but we can't say we are proud if this.
If your objects only contain fields (no methods), this works:
$obj_merged = (object) array_merge((array) $obj1, (array) $obj2);
This actually also works when objects have methods. (tested with PHP 5.3 and 5.6)

Another Way:

foreach($objectA as $k => $v) $objectB->$k = $v;

  • Specify reference or clone
  • Specify first or last entry to take precedence
  • Multiple (more than two) object merging with syntax similarity to array_merge
  • Method linking: $obj->f1()->f2()->f3()...
  • Dynamic composites: $obj->merge(...) /* work here */ $obj->merge(...)
class Compositor {

    protected $composite = array();
    protected $use_reference;
    protected $first_precedence;

    /**
     * __construct, Constructor
     *
     * Used to set options.
     *
     * @param bool $use_reference whether to use a reference (TRUE) or to copy the object (FALSE) [default]
     * @param bool $first_precedence whether the first entry takes precedence (TRUE) or last entry takes precedence (FALSE) [default]
     */
    public function __construct($use_reference = FALSE, $first_precedence = FALSE) {
        // Use a reference
        $this->use_reference = $use_reference === TRUE ? TRUE : FALSE;
        $this->first_precedence = $first_precedence === TRUE ? TRUE : FALSE;

    }

    /**
     * Merge, used to merge multiple objects stored in an array
     *
     * This is used to *start* the merge or to merge an array of objects.
     * It is not needed to start the merge, but visually is nice.
     *
     * @param object[]|object $objects array of objects to merge or a single object
     * @return object the instance to enable linking
     */

    public function & merge() {
        $objects = func_get_args();
        // Each object
        foreach($objects as &$object) $this->with($object);
        // Garbage collection
        unset($object);

        // Return $this instance
        return $this;
    }

    /**
     * With, used to merge a singluar object
     *
     * Used to add an object to the composition
     *
     * @param object $object an object to merge
     * @return object the instance to enable linking
     */
    public function & with(&$object) {
        // An object
        if(is_object($object)) {
            // Reference
            if($this->use_reference) {
                if($this->first_precedence) array_push($this->composite, $object);
                else array_unshift($this->composite, $object);
            }
            // Clone
            else {
                if($this->first_precedence) array_push($this->composite, clone $object);
                else array_unshift($this->composite, clone $object);
            }
        }

        // Return $this instance
        return $this;
    }

    /**
     * __get, retrieves the psudo merged object
     *
     * @param string $name name of the variable in the object
     * @return mixed returns a reference to the requested variable
     *
     */
    public function & __get($name) {
        $return = NULL;
        foreach($this->composite as &$object) {
            if(isset($object->$name)) {
                $return =& $object->$name;
                break;
            }
        }
        // Garbage collection
        unset($object);

        return $return;
    }
}

Usage:

$obj = new Compositor(use_reference, first_precedence);
$obj->merge([object $object [, object $object [, object $...]]]);
$obj->with([object $object]);

Example:

$obj1 = new stdClass();
$obj1->a = 'obj1:a';
$obj1->b = 'obj1:b';
$obj1->c = 'obj1:c';

$obj2 = new stdClass();
$obj2->a = 'obj2:a';
$obj2->b = 'obj2:b';
$obj2->d = 'obj2:d';

$obj3 = new Compositor();
$obj3->merge($obj1, $obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj2:a, obj2:b, obj1:c, obj2:d
$obj1->c;

$obj3 = new Compositor(TRUE);
$obj3->merge($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, obj1:c, obj2:d
$obj1->c = 'obj1:c';

$obj3 = new Compositor(FALSE, TRUE);
$obj3->with($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, #obj1:c, obj2:d
$obj1->c = 'obj1:c';

The best method to merge PHP objects

By Game Changer → Wednesday, December 9, 2015



Choosing a database wrapper in you development project.

Moving an application from one database to another isn't very common, but sooner or later you may find yourself working on another project using a different RDBMS. If you're at home with PDO then there will at least be one thing less to learn at that point.

Apart from that I find the PDO API a little more intuitive, and it feels more truly object oriented. mysqli feels like it is just a procedural API that has been objectified, if you know what I mean. In short, I find PDO easier to work with, but that is of course subjective.
PDO is the standard, it's what most developers will expect to use. mysqli was essentially a bespoke solution to a particular problem, but it has all the problems of the other DBMS-specific libraries. PDO is where all the hard work and clever thinking will go.

Here are the results of the tests. Lower values are better, of course.

PDO results for 0.1M SQL queries

Query Time in seconds
insert 15.23874929331
select 18.29382394421
update 14.93284923728
delete 17.92102038303
MySQLi results for 100k queries

Query Time in seconds
insert 21.98739839490
select 26.01564064026
update 27.35169916153
delete 21.15891308745

PDO results for 1M queries
Query Time in seconds
insert 139.2347803431
select 207.1249543506
update 151.2345734537
delete 141.3245435434
MySQLi results for 1M queries

Query Time in seconds
insert 204.2342353454
select 291.4354655432
update 221.0213423434
delete 231.1456456456

PDOMySQLi
Database support12 different driversMySQL only
APIOOPOOP + procedural
ConnectionEasyEasy
Named parametersYesNo
Object mappingYesYes
Prepared statements 
(client side)
YesNo
PerformanceFastFast
Stored proceduresYesYes
This is another important feature that PDO has; binding parameters is considerably easier than using the numeric binding:
$params = array(':username' => 'test', ':email' => $mail, ':last_login' => time() - 3600);
     
$pdo->prepare('
    SELECT * FROM users
    WHERE username = :username
    AND email = :email
    AND last_login > :last_login');
     
$pdo->execute($params);
...opposed to the MySQLi way:
The question mark parameter binding might seem shorter, but it isn't nearly as flexible as named parameters, due to the fact that the developer must always keep track of the parameter order; it feels "hacky" in some circumstances.
Unfortunately, MySQLi doesn't support named parameters.

MySQLi vs PHP Object Mapping


Both PDO and MySQLi can map results to objects. This comes in handy if you don't want to use a custom database abstraction layer, but still want ORM-like behavior. Let's imagine that we have a User class with some properties, which match field names from a database.

class User {
    public $id;
    public $first_name;
    public $last_name;
     
    public function info()
    {
        return '#'.$this->id.': '.$this->first_name.' '.$this->last_name;
    }
} 

API Case:

Both offer an object-oriented API, but MySQLi also offers a procedural API - which makes it easier for newcomers to understand. If you are familiar with the native PHP MySQL driver, you will find migration to the procedural MySQLi interface much easier. On the other hand, once you master PDO, you can use it with any database you desire!

Summery:

After the whole reviewing, PDO wins this battle with ease. With support for twelve different database drivers (eighteen different databases!) and named parameters. We can ignore the small performance loss, and get used to its API. Also from a security point.

PDO or MySqli: The pros and cons

By Game Changer → Tuesday, December 8, 2015