Query Mysql_PHP tutorial using PDO class in php

WBOY
Release: 2016-07-13 17:18:43
Original
1021 people have browsed it

In my PHP development process, the database uses the mysql database. Database-related operations basically use the mysql extension functions in php, such as mysql_query, mysql_connect and other functions. These traditional methods are used to connect and query the database. At that time, I personally felt that there were two disadvantages. One is that it has no scalability, that is, it can only be used in mysql database. If you want to change the database, the PHP extension functions used are different. If you want to change the database during the development process, then all the same Database-related operations have to be redone; the second is that if the filtering statements are not strict, there will be the risk of SQL injection, causing the website to be maliciously attacked and out of control. Although the mysql_real_escape_string() function is used to filter user-submitted values, it also has flaws. By using the prepare method of PHP's PDO extension, you can effectively avoid the risk of sql injection.


1. Introduction to PDO

The PDO extension defines a lightweight, consistent interface for PHP to access databases. It provides a data access abstraction layer so that no matter what database is used, queries and data can be obtained through consistent functions. PDO is released with PHP5.1 and can also be used in the PECL extension of PHP5.0, but cannot run on previous PHP versions. Compared with mysql and mysqli, PDO makes cross-database use more friendly.


2. PDO installation and configuration

In php5.2.10, php has pdo installed by default.

Open the php.ini file, find the sentence extension=php_pdo.dll, remove the previous comment symbol, and then restart apache. If you don't find this sentence, you can add it yourself or check whether the system uses the dynamic link library file .so during installation. If so, you can find a conf.d folder in the php directory, and there is a pdo below. ini link file, if there is a sentence extension=pdo.so in it, it means that PDO has been enabled.

To verify whether PDO has been enabled in PHP, first write a script with the content

<?php
        phpinfo();
?>
Copy after login

If the displayed results contain the following content, it means that the PDO extension has been enabled.


3. Create a PDO object

__construct(string dsn[,string username [,string password [, array driver_options]]]);//pdo的构造方法
Copy after login
Parameter analysis: The first required parameter is the data source name DSN, which is used to define a certain database and the driver that must be used.

For example, the DSN formats for connecting the oracle server and mysql server are as follows:

ocl:dbname=//127.0.0.1:1521/mydb //DSN to connect to Oracle server, oci: as driver prefix, host 127.0.0.1, port 1521, database mydb

mysql:host=127.0.0.1;dbname=testdb //DSN to connect to Mysql server, mysql: as driver prefix, host 127.0.0.1, database testdb

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';

	$user = 'root';

	$password = 'root';

	try {
		$dbh = new PDO($dsn, $user, $password);
	}catch(PDOException $e) {
		echo "connect failed: ".$e->getMessage();
	}
Copy after login

4. PDO setting properties

1) PDO has three error handling methods:

? PDO::ERrmODE_SILENT does not display error information, only sets error code
? PDO::ERrmODE_WARNING displays warning error
? PDO::ERrmODE_EXCEPTION throws an exception

You can use the following statement to set the error handling method to throw an exception

$dbh->setAttribute(PDO::ATTR_ERrmODE, PDO::ERrmODE_EXCEPTION);
Copy after login
When set to PDO::ERrmODE_SILENT, you can get error information by calling errorCode() or errorInfo(), of course, it can also be used in other situations.

2) Because different databases handle the case of returned field names differently, PDO provides the PDO::ATTR_CASE setting item (including PDO::CASE_LOWER, PDO::CASE_NATURAL, PDO::CASE_UPPER) to determine the returned field name. Upper and lower case.

3) Specify the corresponding value in php for the NULL value returned by the database by setting the PDO::ATTR_ORACLE_NULLS type (including PDO::NULL_NATURAL, PDO::NULL_EmpTY_STRING, PDO::NULL_TO_STRING).


5. Common PDO methods and their applications
PDO::query() is mainly used for operations that return recorded results, especially SELECT operations
PDO::exec() is mainly used for operations that do not return a result set, such as INSERT, UPDATE and other operations
PDO::prepare() is mainly a preprocessing operation. You need to use $rs->execute() to execute the SQL statement in the preprocessing. This method can bind parameters and is relatively powerful (preventing SQL injection depends on this)
PDO::lastInsertId() returns the last insert operation, the primary key column type is the last auto-increment ID
PDOStatement::fetch() is used to get a record
PDOStatement::fetchAll() is to get all recordsets into a collection
PDOStatement::fetchColumn() is a field of the first record specified in the fetch result. The default is the first field
PDOStatement::rowCount(): Mainly used for the result set affected by PDO::query() and PDO::prepare()'s DELETE, INSERT, and UPDATE operations. It is invalid for the PDO::exec() method and SELECT operation.


6. PDO operation MYSQL database instance

$sql = "UPDATE article SET title="haha" WHERE id=1";

$affected = $dbh->exec($query);

if($affected) {
	echo "successed";
}else {
	print_r($dbh->errorINdo());
}
Copy after login

Preprocessing method:

$SQLStatament = "INSERT INTO article VALUES(":title, :content")";
$param = array(":title" => "something",
				":content" => "aaaa");
//准备的参数,对应数据库的字段

$stmt = $dbh->prepare($SQLStatement);

$stmt->execute($param);
Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/621626.htmlTechArticleIn my PHP development process, the database is all based on mysql database, and the operations related to the database are basically They all use the mysql extension function in php, such as mysql_query, mysql_co...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template