Home > Article > Backend Development > Is it okay to use pdo for php?
PDO - The abbreviation of PHP Data Object (PHP Data Object), as a way to provide a unified connection interface for multiple databases, the bottom layer of PDO needs to cooperate with the PDO data driver of the corresponding database to operate the database. PDO is the database connection method officially recommended by PHP today. Its advantages are:
PHP Programming from entry to proficiency)
2. PDO supports more advanced DB feature operations, such as: scheduling of stored procedures, etc., which is not supported by the mysql native library.3. PDO is the official PECL library of PHP. Its compatibility and stability must be higher than MySQL Extension. You can directly use the pecl upgrade pdo command to upgrade. 4. PDO can prevent SQL injection and ensure that the database is more secure. The principle of PDO preventing SQL injectionAfter PHP 5.1.0, PDO is enabled by default. You can check the opening status of PDO through the phpinfo() function:PDO Preset Processing
When we use the database to execute a query, the database management system (DBMS) will compile the query and optimize the query. Using PDO preprocessing can make this process only happen when the first query is made. In subsequent identical queries, only the bound parameters need to be replaced, thus saving the time of repeated compilation. In addition, using PDO parameter binding can also avoid security issues such as SQL injection. Code demonstration:<?phptry{ $dbh=new PDO('mysql:host=localhost;dbname=testDB','root',''); $stmt=$dbh->prepare("INSERT users (user_name,sex) VALUES (:user_name,:sex)"); $stmt->bindParam(':user_name',$name); $stmt->bindParam(":sex",$sex); //插入一行 $name="yang001"; $sex="M"; $stmt->execute(); //再次插入一行 $name="yang002"; $sex="F"; $stmt->execute(); }catch (PDOException $e){ print "Error ! : ".$e->getMessage(); die(); }View the database results as follows:
We use preprocessed query statements to retrieve the results:
<?phptry{ $dbh=new PDO('mysql:host=localhost;dbname=testDB','root',''); $stmt=$dbh->prepare("SELECT * FROM users WHERE user_name=:user_name "); $stmt->bindParam(':user_name',$name); //插入一行 $name="yang001"; if($stmt->execute()){ while ($row=$stmt->fetch(PDO::FETCH_ASSOC)){ print_r($row); } } }catch (PDOException $e){ print "Error ! : ".$e->getMessage(); die(); }The results are as follows :
##
The above is the detailed content of Is it okay to use pdo for php?. For more information, please follow other related articles on the PHP Chinese website!