Home >Backend Development >PHP Tutorial >PDO operation MySQL method guidance under PHP
This article mainly introduces the method of PHP PDO operating MySQL. It analyzes in detail the operating techniques related to PHP opening PDO and database creation, connection, addition, deletion, modification and query in the form of examples. Friends in need can refer to the following
This article describes how PHP PDO operates MySQL through examples. Share it with everyone for your reference, as follows:
The PDO extension in PHP defines a lightweight, consistent interface for PHP to access the database. It provides a data access abstraction layer, so that no matter No matter what database you use, you can perform queries and obtain data through consistent functions.
The PHP version supported by PDO is PHP5.1 and higher, and PDO is enabled by default under PHP5.2.
The following is the configuration of PDO in php.ini:
extension=php_pdo.dll
In order to enable support for a certain database, you need to open the corresponding extension in the php configuration file. For example, to support MySQL, you need to open the following extension
extension=php_pdo_mysql.dll
The following is to use PDO to perform basic add, delete, modify and query operations on mysql
Create a test database, and then run the following SQL statement:
DROP TABLE IF EXISTS `test`; CREATE TABLE `test` ( `id` int(10) NOT NULL DEFAULT '0', `user` char(20) DEFAULT NULL, PRIMARY KEY (`id`), KEY `idx_age` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Program code:
<?php header("content-type:text/html;charset=utf-8"); $dsn="mysql:dbname=test;host=localhost"; $db_user='root'; $db_pass='admin123'; try{ $pdo=new PDO($dsn,$db_user,$db_pass); }catch(PDOException $e){ echo '数据库连接失败'.$e->getMessage(); } //新增 $sql="insert into test (id,user) values (1,'phpthinking')"; $res=$pdo->exec($sql); echo '影响行数:'.$res; //修改 $sql="update test set user='phpthinking' where id=1"; $res=$pdo->exec($sql); echo '影响行数:'.$res; //查询 $sql="select * from test"; $res=$pdo->query($sql); foreach($res as $row){ echo $row['user'].'<br/>'; } //删除 $sql="delete from test where id=1"; $res=$pdo->exec($sql); echo '影响行数:'.$res;
The above is the detailed content of PDO operation MySQL method guidance under PHP. For more information, please follow other related articles on the PHP Chinese website!