search
HomeBackend DevelopmentPHP TutorialQuery Mysql_PHP tutorial using PDO class in php

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();
?>

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的构造方法
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();
	}

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);
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());
}

Preprocessing method:

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

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

$stmt->execute($param);

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...
Statement
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
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

CS玩家的首选:推荐的电脑配置CS玩家的首选:推荐的电脑配置Jan 02, 2024 pm 04:26 PM

1.处理器在选择电脑配置时,处理器是至关重要的组件之一。对于玩CS这样的游戏来说,处理器的性能直接影响游戏的流畅度和反应速度。推荐选择IntelCorei5或i7系列的处理器,因为它们具有强大的多核处理能力和高频率,可以轻松应对CS的高要求。2.显卡显卡是游戏性能的重要因素之一。对于射击游戏如CS而言,显卡的性能直接影响游戏画面的清晰度和流畅度。建议选择NVIDIAGeForceGTX系列或AMDRadeonRX系列的显卡,它们具备出色的图形处理能力和高帧率输出,能够提供更好的游戏体验3.内存电

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools