: This article mainly introduces common methods for PDO database operations. if you are interested in the PHP Tutorial, refer to it. 1. read the definition of PDO first:
PDOExtension to PHPAccess DatabaseDefines a lightweight and consistent interface, which provides a data access abstraction layer, so that no matter what database is used, data can be queried and retrieved through consistent functions. PDO is released with PHP5.1 and can also be used in the PECL extension of PHP5.0, and cannot run in the previous PHP version.
In this case, I marked the important areas in bold.
2. database connection
The PDO connection is simple, with only four parameters: data source information (DSN), user name, password, and parameter array.
Instance:
'SET NAMES \'UTF8\'',PDO::ATTR_ERRMODE => PDO::ERRMODE_Exception));?>
If a connection error occurs, PDO is thrown.ExceptionException. The reference code is as follows:
try{ $params = array ( PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'' , PDO::ATTR_ERRMODE => PDO::ERRMODE_Exception, ); $dbh = new PDO('mysql:host='.$mysql_server_name.';dbname='.$mysql_database, $mysql_username, $mysql_password,$params); echo"DB Connect OK!!!".'
';}catch(PDOException $e){ echo"DB Connect Error!!!".$e->getMessage(); exit;}
3. execute the query:
$ SQL = 'SELECT pid, pname from project_list '; foreach ($ dbh-> query ($ SQL) as $ row) {// data in the output result set echo $ row ['pid'].'
'; Echo $ row ['pname'].'
';}
4. execute updates.
$ SQL = 'Insert into project_list (pname) values (\ 'tianxin \ ')'; $ rows = $ dbh-> exec ($ SQL); echo 'Updated '. $ rows. 'line
'; Echo "the final automatic number is:". $ dbh-> lastInsertId ()."
";
The above describes the common methods of PDO database operations, including the content, and hope to be helpful to friends who are interested in PHP tutorials.