The use of pdo in php

Keywords: PDO SQL Database PHP

Step 1: Test whether pdo is enabled:

Run the following code to indicate that the PDO has been installed if the parameter is wrong. If the description object does not exist, modify the PHP configuration file php.ini and cancel the previous comment on php_pdo_yourssqlserverhere.extis.

$test=new PDO();
Warning: PDO::__construct() expects at least 1 parameter, 0 given in D:\wamp64\www\test\test.php on line 

The above error hints lack of parameters, indicating that the pdo installation was successful!

Step 2: Connect to the database

$dsn = 'mysql:dbname=demo;host=localhost;port=3306';
$username = 'root';
$password = '123456';
try {
    $db = new PDO($dsn, $username, $password); 
} catch(PDOException $e) {
    die('Could not connect to the database:
' . $e);
}

Step 3: Basic Query

Using query and exec in PDO makes database query very simple. If you want to get the number of rows of the query results exec is very useful, so SELECT query statement is very useful.

$statement = <<<SQL
    SELECT *
    FROM `student`
    WHERE `class` = 1
SQL;

$rows = $db->query($statement);

If the above query is correct, then $rows is now a PDO Statement object from which we can get the results we need and how many result sets have been queried.

Step 4: Get the number of rows

If the Mysql database is used, the PDO Statement contains a rowCount method to get the number of rows in the result set, as shown in the following code:

echo $rows->rowCount();

Step 5: Traverse the result set

    foreach($rows->FetchAll(PDO::FETCH_ASSOC) as $row) {
        echo "<pre>";
            print_r($row);
        echo "</pre>";
    }

PDO also supports the Fetch method, which returns only the first result.

Note: Escape special characters entered by users

PDO provides a method called quote, which can escape special characters from quoted places in input strings.

$input= this is's' a '''pretty dange'rous str'ing
$db->quote($input);
//Output:'this is\'s\' a \'\'\'pretty dange\'rous str\'ing'

Use exec() to get the number of rows affected

PDO can use exec() method to implement UPDATE,DELETE and INSERT operations. After execution, it will return the number of affected rows:

$statement = <<<SQL
    DELETE FROM `student`
    WHERE `class` = 1;
SQL;
echo $db->exec($statement);

Preprocessing statement:

Although exec method and query are still widely used and supported in PHP, PHP official website still requires people to replace them with preprocessed statements. Why? The main reason is: it's safer. Preprocessing statements do not insert parameters directly into actual queries, which avoids many potential SQL injections.
However, for some reason, PDO does not actually use preprocessing. It simulates preprocessing and inserts parameter data into the statement before passing it to the SQL server, which makes some systems vulnerable to SQL injection.
If your SQL server does not really support preprocessing, we can easily fix this problem by passing parameters during PDO initialization as follows:

$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

Here is our first preprocessing statement:

$statement = $db->prepare('SELECT * FROM student WHERE `name`=? AND `class`=?');
$statement2 = $db->prepare('SELECT * FROM student WHERE `name`=:name AND `class`=:class)';

As shown in the code above, there are two ways to create parameters, named and anonymous (not in a statement at the same time). Then you can use bindValue to type in your input:

$statement->bindValue(1, 'Cake');
$statement->bindValue(2, 1);
$statement2->bindValue(':name', 'user');
$statement2->bindValue(':class', 1);

Note that when using named parameters, you need to include a colon (:). PDO also has a bindParam method, which can refer to bound values, that is, it only finds the corresponding values when the statement is executed.
The only thing left to do now is to execute our sentences:

$statement->execute();
$statement2->execute();

//Get our results:
$cake = $statement->Fetch();
$pie  = $statement2->Fetch();

To avoid using only code fragments brought about by bindValue, you can use arrays to execute methods as parameters, like this:

$statement->execute(array(1 => 'Cake', 2 => 1));
$statement2->execute(array(':name' => 'Pie', ':class' => 1));

Transaction mechanism:

One transaction is to execute a set of queries without saving their impact on the database. The advantage is that if you execute four interdependent insert statements, when one fails, you can roll back so that other data cannot be inserted into the database to ensure that the interdependent fields can be inserted correctly. You need to make sure that the database engine you use supports transactions. But it does not roll back all types (for example, using DROP TABLE in MySQL), which is not really reliable, and I recommend avoiding relying on it as much as possible.

try {  
  $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $db->beginTransaction();
  $db->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  $db->exec("insert into salarychange (id, amount, changedate) 
      values (23, 50000, NOW())");
  $db->commit();

} catch (Exception $e) {
  $db->rollBack();
  echo "Failed: " . $e->getMessage();
}
?> 

Other useful options

PDO::ATTR_DEFAULT_FETCH_MODE
 You can choose what type of result set PDO will return, such as PDO::FETCH_ASSOC, which will allow you to use $result['column_name'], or PDO::FETCH_OBJ, which will return an anonymous object so that you can use $result-> column_name.
    $pdo=new PDO("mysql:host=localhost;dbname=test",'root','123456');
    $pdo->exec('set names utf8');
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
    $statement = "select * from student";
    $rows = $pdo->query($statement);
    var_dump(get_magic_quotes_gpc()) ;

    echo "<pre>";
    echo "<pre>";
    print_r($rows->rowCount());
    echo "</pre>";
    foreach($rows->FetchAll() as $row) {
        echo "<pre>";
            print_r($row);
        echo "</pre>";
    }

After the query statement, you don't have to set the mode of getting the result every time, is it once and for all?

Posted by pstevereynolds on Mon, 25 Mar 2019 01:57:27 -0700