当前位置:网站首页>Differences of several query methods in PDO

Differences of several query methods in PDO

2022-06-13 03:14:00 wks19891215

(1)exec

php The description in the manual is : To perform a SQL sentence , And return the number of rows affected .

It can be seen from it that ,execute It can be applied to “ Additions and deletions ” Additions, deletions and modifications in . Because the query operation will return a result set , and exec Function can only return the affected function .

(2)query

Corresponding to “ Additions and deletions ” Medium “ check ”. Used to execute once sql sentence , Return to one PDOStatement Result set . This result can be considered as a multidimensional array , You can use it directly .

(3)prepare

For repeated statements , have access to prepare Make a pretreatment ( Optimize ). Because each query statement needs to be compiled before execution , adopt prepare after , It can save the cost of repeatedly compiling query statements . First prepare Again execute. This returns a PDOStatement Result set ,PDOStatement It's an object , You can use its member methods to handle the result set . Depending on the result set type , It can also be used directly as a multidimensional array .

If prepare Incoming sql If the statement is mutable , Can pass bindParam To bind parameters to , then execute.

PS:prepare+execute The combination of , Can be applied to “ Additions and deletions ” All operations .


Let's take a look at specific usage examples :

<?php
$dsn      = "mysql:dbname=pdo;host=localhost";
$user     = "root";
$password = "root";
$dbh      = new PDO($dsn, $user, $password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// Use exec To add, delete, or modify 
$sqlcmd = "insert into userinfo values (rand(),rand())";
$dbh->exec($sqlcmd);

// Use query Query operation 
$sqlcmd = "select * from userinfo";
try {
    $data = $dbh->query($sqlcmd);
    foreach ($data as $row) {
        print_r($row);
        echo '<br>';
    }
}
catch (PDOException $e) {
    echo $e->getMessage();
}

//prepare First pretreatment , Then bind the parameters , then execute
$sqlcmd     = 'select  password from userinfo where username = :pname';
$res        = $dbh->prepare($sqlcmd);
$puser_name = "aaa";
$res->bindParam(':pname', $puser_name, PDO::PARAM_STR, 200);
$res->execute();
foreach ($res as $row) {
    print_r($row);
    echo "<br>";
}

?>

This is just the most basic use case . Generally speaking , It will be used in specific projects PDO Wrapper class , Some frames such as zendframework It also comes with its own database processing class .

原网站

版权声明
本文为[wks19891215]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280532254217.html