search
HomeBackend DevelopmentPHP Tutorialphp使用PDO方法详解_php技巧

本文详细分析了php使用PDO方法。分享给大家供大家参考。具体分析如下:

PDO::exec:返回的是int类型,表示影响结果的条数.

复制代码 代码如下:
PDOStatement::execute

返回的是boolean型,true表示执行成功,false表示执行失败,这两个通常出现在如下代码:

复制代码 代码如下:
$rs0 = $pdo->exec($sql);
$pre = $pdo->prepare($sql);
$rs1 = $pre->execute();

一般情况下可以用$rs0的值判断SQL执行成功与否,如果其值为false表示SQL执行失败,0表示没有任何更改,大于0的值表示影响了多少条记录.

但是$rs1只能返回SQL执行成功与否,如果需要获取影响的记录数需要使用$pre->rowCount();

我个人喜欢使用 MySQL,所以我的 extensions.ini 中有这二行.

复制代码 代码如下:
extension=pdo.so
extension=pdo_mysql.so

接著在程式中,代码如下:

复制代码 代码如下:
define('DB_NAME','test');
define('DB_USER','test');
define('DB_PASSWD','test');
define('DB_HOST','localhost');
define('DB_TYPE','mysql');
$dbh = new PDO(DB_TYPE.':host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASSWD);

文中的使用常数设定是我个人的习惯,各位不用像我这么麻烦,当像上面的操作,$dbh 本身就是代表了PDO的连线了,那要怎样使用PDO呢?

第一种,懒人法 query,什么都不用想,像平常一样的使用 query 的函式,代码如下:

复制代码 代码如下:
$sql = 'select * from test';
foreach ( $dbh->query($sql) as $value)
{
    echo $value[col];
};

第二种,自动带入法 prepare,我个人使用PDO后,偏好利用 prepare 的函式来进行作动 prepare 的好处是可以先写好 SQL 码,并且在稍后自动带入我们要的资料.

这个我想最大的好处是比起直接利用 query 可以减少许多安全性的问题,首先,我们利用 prepare 进行 SQL 码的设定,在利用bindparm 来进行设定的动作,代码如下:

复制代码 代码如下:
$sth = $dbh->prepare('update db set zh_CN= :str where SN=:SN');
$sth->bindParam(':str',$str,PDO::PARAM_STR,12);
$sth->bindParam(':SN',$SN);
$sth->execute();

请注意文中的 :str 及 :SN,当我们利用 bindParam的函式,可以利用 :word 来指定系统需要套用的部份,像是我们利用:str 及 :SN 来指定,而实际的内容,就靠bindParam还可以指定我们要输入的型态。

首先我们先看 :str 的指定,:str 由於我确定资料是属於文字,因此利用 PD::PARAM_STR 来告诉程式“这个是字串哟”,并且给一个范围,也就是长度是12个位元。

我们也可以不要那么复杂,像 :SN,虽然也是用 bindParam 来指定,但是我们省略了型态及长度,PHP 会用该变数预设的型态来套用.

最后呢,就是利用 $sth->execute(); 来进行执行的动作,基本上不难,甚至可以说很简单呢.

如果你有大量需要重复套用的资料,你就可以拼了命的重新利用 bindParam 来指定,比如我的:str 及 :SN 如果有十笔资料,我也可以这样子直接新增到资料库,代码如下:

复制代码 代码如下:
$sth = $dbh->prepare('insert into db ("zh_CN","zh_TW")values(:str , :SN');
foreach ($array => $value )
{
 $sth->bindParam(':str',$value[str],PDO::PARAM_STR,12);
 $sth->bindParam(':SN',$value[SN]);
 $sth->execute();
}

甚至强者如我朋友,把所有可能的 SQL 全写在一个档案后面,后来的过程SQL的部份就变成全用变数带进去了,反正资料可以用现成的方式套用嘛.

那,如果利用 prepare 的方式来 select,关键字当然也可以像上面的方式利用:word 来指定,代码如下:

复制代码 代码如下:
$sth = $dbh->prepare('select * from db where SN = :SN');
$sth->bindParam(':SN',$value[SN]);
$sth->execute();
while($meta = $sth->fetch(PDO::FETCH_ASSOC))
{
 echo $meta["name"];
}

这样新出现的是 fetch,跟mysql_fetch_row() 的意思差不多,但是在 fetch() 中我们发现多了一个 PDO::FETCH_ASSOC 这个东西.

fetch() 提供了许多获取资料的方式,而 PDO::FETCH_ASSOC 指的就是传回下一笔资料的栏位名及值啦

比如上例,利用 $meta 来取得 fetch 传回的资料,此时 $meta 的元素名称就是资料库的栏位名称,而内容当然就是值本身这个跟你利用 mysql_fetch_row() 时不一样,因为除了栏位名称,mysql_fetch_row() 还会依照顺利将元素名称除了栏位外在多给予一个以序号的方式为基础的元素,那难道 PDO 没有吗?

当然有,只要将 PDO::FETCH_ASSOC 改为 PDO::FETCH_BOTH,那用法就跟 mysql_fetch_row() 没什么两样了.

如何除错

除错是所有程式设计师中心中永远的痛,我们使用 PDO 要如何除错呢?

其实 PDO 已经提供了二个非常方便的函式 errorInfo() 及 errorCode()

用法也是世界简单,每当我们利用 execute() 执行后,如果有错误,那 errorInfo() 及 errorCode() 中就会有内容,我们就可以这样子做,代码如下:

复制代码 代码如下:
$sth = $dbh->prepare('select * from db where SN = :SN');
$sth->bindParam(':SN',$value[SN]);
$sth->execute();
if ($sth->errorCode())
{
 echo "有错误!有错误!";
 print_r($sth->errorInfo());
}

而 $sth->errorInfo() 会是一个阵列,这个阵列有三个值:

0 为SQLSTATE error code

1 为你所使用的 Driver 所传回的错误码

2 为你所使用的 Driver 所传回的错误讯息

希望本文所述对大家的php程序设计有所帮助。

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 vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use