The PDO php mysql database connection, CRUD etc. operations Examples

We use traditional mysql_connect, mysql_query method to query the database connection, if there is strict filtering SQL injection risk, leading to the site was attacked.

Although with the mysql_real_escape_string () function filtering value submitted by the user, but there are drawbacks.

The use PHP's PDO extension prepare method, you can avoid sql injection risk.

PDO (PHP Data Object) is a major feature PHP5 newly added, since PHP 5 extension in previous php4 / php3 are a bunch of database connections and handle with each database.

As php_mysql.dll. PHP6 default will also connect the PDO, mysql will be extended as an auxiliary.

Official: http://php.net/manual/en/book.pdo.php

 

1, before using PDO connection need to confirm whether the PDO extension has been opened.

        Before using the PDO extension, first enable this extension, PHP.ini in.

Remove the " Extension = php_pdo.dll front" and ";" number, to connect to the database, need to remove the front associated with the database expansion PDO ";" number.

(Generally used in php_pdo_mysql.dll ), and then restart the Apache server. 

extension=php_pdo.dll
extension=php_pdo_mysql.dll

2, PDO database connection:

<?php
class Index
{  
    Private $ config = [
          // database type 
        ' type '             => ' MySQL ' ,
         // server address 
        ' hostname '         => ' 127.0.0.1 ' ,
         // database name 
        ' Database '         => ' Test ' ,
         // username 
        ' username '         => ' the root ' ,
         // password 
        'password'        => ' The root ' ,
         // port 
        ' HostPort '         => ' 3306 ' ,
         // database using default encoding UTF8 
        ' charset '          => ' UTF8 ' ,
    ];
    private $pdo;
    public function __construct()
    {
        $dsn = "{$this->type}:host={$this->hostname};port={$this->hostport};";
        $dsn.= "dbname={$this->database};charset={$this->charset}";
        $pdo = new PDO($dsn, $this->username, $this->password);
        $pdo->setAttribute(PDO::ATTR_CASE, PDO::CASE_LOWER);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $this->pdo = $pdo;
        unset($dsn);
    }
    public function demo()
    {
        $sql = 'select id,name from goods';
        $goods = $this->pdo->query($sql);
        $goods = $goods->fetchAll(PDO::FETCH_ASSOC);
 
        # Print the output data
        print_r($goods);
    }
}

3, PDO setting properties:

 PDO There are three options for handling errors:

1, PDO :: ERrmODE_SILENT  no error messages, only error code set

2, PDO :: ERrmODE_WARNING  display a warning wrong

3, PDO :: ERrmODE_EXCEPTION  thrown

1
$pdo->setAttribute(\PDO::ATTR_ERrmODE, \PDO::ERrmODE_EXCEPTION);

1)  : When set to PDO :: ERrmODE_SILENT can call errorCode () or errorInfo () to get the error message, of course, other situations can be.

2)  : Because different database field name in case the processing returns different, provided PDO PDO :: ATTR_CASE settings (including PDO :: CASE_LOWER, PDO :: CASE_NATURAL, PDO :: CASE_UPPER), to determine the field names returned case.

3)  : NULL value is specified in the database returns the corresponding value provided by php PDO :: ATTR_ORACLE_NULLS types (including PDO :: NULL_NATURAL, PDO :: NULL_EmpTY_STRING, PDO :: NULL_TO_STRING).

 

4, PDO used and its application:

 

PDO :: query ()  operation is mainly used to record the results returned, especially SELECT operation

PDO :: exec ()  is mainly a collection of no results returned for operations such as INSERT, UPDATE other operations

PDO :: prepare ()  mainly pretreatment operation is required> execute () to perform pre-processing SQL statements inside by $ rs-, this method can bind parameters, more powerful (to prevent sql injection to rely on this)

PDO :: lastInsertId ()  Returns the last insert operation, the primary key column is the last self-energizing type ID of the self-energizing

PDOStatement :: fetch ()  is used to get a record

PDOStatement :: fetchAll ()  is set to get a collection of all records

PDOStatement :: fetchColumn ()  is to obtain the results of the first record of a field is specified, the default is the first field

PDOStatement :: rowCount ()  is mainly used for PDO :: query () and PDO :: prepare () for DELETE, INSERT, UPDATE operations affect the result set, the invalid PDO :: exec () method and SELECT operations.

 

5, PDO operation example:

 

[Example 6] described anti sql injection operations:

 

1, when accessing a MySQL database using the PDO, the case is not in use genuine real prepared statements default.

To solve this problem, you must disable the simulation results prepared statements.

2, setting disables the prepared statements: $ pdo-> setAttribute (\ PDO :: ATTR_EMULATE_PREPARES, false); 

 

It tells PDO disabled emulated prepared statement, and use real parepared statements.

This ensures that the SQL statements and the corresponding values ​​before being passed to the PHP mysql server will not be resolved (banned all possible malicious SQL injection attacks).

Although you can set up a configuration file attribute character set (charset = utf8), but need extra attention that older versions of PHP (<5.3.6) is to ignore a character argument in the DSN.

 

But we need to pay attention to the following situations, PDO does not help us to prevent SQL injection:

1, you can not let a placeholder instead of a set of values, such as?:

select * from xc_company where id in( ? );

2, you can not let a placeholder instead of a data table or column names, such as:

select * from xc_company order by ?;

3, you can not make any other placeholders instead of SQL syntax, such as?:

select EXTRACT( ? from date) as times from xc_company;

View PDO are those

echo '<pre>';
print_r(get_class_methods('PDO'));
echo '</pre>';

result:

Array
(
    [0] => __construct
    [1] => prepare
    [2] => beginTransaction
    [3] => commit
    [4] => rollBack
    [5] => inTransaction
    [6] => setAttribute
    [7] => exec
    [8] => query
    [9] => lastInsertId
    [10] => errorCode
    [11] => errorInfo
    [12] => getAttribute
    [13] => quote
    [14] => __wakeup
    [15] => __sleep
    [16] => getAvailableDrivers
)

Common examples of source code:

<?php
 
PDO connection [#] mysql database (database name: lmgg, Account: root, password: root)
$pdo = new \PDO('mysql:host=localhost;dbname=lmgg;charset=utf8','root','root'); 
# Set the database encoded as UTF - . 8 (prevent distortion) course, the above connection is provided.
# Above may be provided or not provided, there is no charset = UTF8 can be connected to the database
$pdo->exec('set names utf8'); 
 
 
 
 
 
Example # 1 [: data] Query: Query table id and company name fields. To deposit $ data array to
$res = $pdo->query("select id,name from xc_company"); 
$data = [];
 
# 1 : FETCH_ASSOC array form associated return
# 2 : FETCH_NUM numerically indexed array of return
Set the return data type Method # 1:
$res->setFetchMode(\PDO::FETCH_NUM); 
while($row = $res->fetch()){
    $data[] = $row;
}
echo '<pre>';
print_r($data);
echo '</pre>';
 
# Set the return data type Method 2:
while($row = $res->fetch(\PDO::FETCH_ASSOC)){
    $data[] = $row;
}
echo '<pre>';
print_r($data);
echo '</pre>';
 
 
 
 
[Example # 2: Add Data]: Add to company data table, and returns the data in the table is the ID number!
RES $ = $ PDO-> Exec ( " INSERT INTO xc_company (name) values ( 'Ogawa programmed to add 111') " );
 IF ($ RES) {
    echo ' . 11 successful data ID is added: ' $ PDO-> lastInsertId ().. ' a ' ;
}
RES $ = $ PDO-> Query ( " INSERT INTO xc_company (name) values ( 'Ogawa programmed to add 222') " );
 IF ($ RES) {
    echo ' 22 is successfully added to data ID: ' $ PDO-> lastInsertId ().. ' a ' ;
}
 
 
 
 
 
[Example # 3: Updating Data]:
RES $ = $ PDO-> Exec ( " Update xc_company SET name = 'Ogawa update program 111' WHERE ID = 26 is " );
 IF ($ RES) {
    echo ' update data a success ' ;
}
RES $ = $ PDO-> Query ( " Update xc_company SET name = 'Ogawa update program 222' WHERE ID = 26 is " );
 IF ($ RES) {
    echo ' successfully updated data [ ' $ RES-> the rowCount ().. ' ] Article a ' ;
}
 
 
 
 
 
 
[Example # 4: Delete Data]:
$res = $pdo->exec("delete from xc_company where id=38");
if($res){
    echo ' Delete a successful data ' ;
}
$res = $pdo->query("delete from xc_company where id=38");
if($res){
    echo ' successfully deleted data [ ' $ RES-> the rowCount ().. ' ] Article a ' ;
}
 
 
 
 
 
[Example # 5: Statistics]: statistical table how many data company
$num = $pdo->query("select count(*) from xc_company");
echo ' Total Data: [ ' . $ num-> fetchColumn (). ' ] Article ' ;
 
 
 
 
 
# [Example 6: Anti sql injection]: instance, look at the text before use, a more thorough understanding of the will!
# PDO connection mysql database (database name: lmgg, Account: root, password: root)
$pdo = new \PDO("mysql:host=localhost; dbname=lmgg", "root", "root");
# Disable prepared statements of simulation results
$pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false); 
$pdo->query("set names 'utf8'");
$sql="select * from xc_company where name = ?";
$res = $pdo->prepare($sql);
name $ = ' Ogawa programming ' ;
$exeres = $res->execute(array($name));
$data = [];
if($exeres){
    while ($row = $res->fetch(\PDO::FETCH_ASSOC)){
       $data[] = $row;
    }
}
echo '<pre>';
print_r($data);
echo '</pre>';
$pdo = null;
 
?>

Guess you like

Origin www.cnblogs.com/missbye/p/12165930.html
Recommended