Home Backend Development PHP Tutorial php中mysql连接方式PDO使用详解_php技巧

php中mysql连接方式PDO使用详解_php技巧

May 16, 2016 pm 08:22 PM
mysql pdo php

PDO常用方法:

PDO::query()主要用于有记录结果返回的操作(PDOStatement),特别是select操作。

PDO::exec()主要是针对没有结果集合返回的操作。如insert,update等操作。返回影响行数。
PDO::lastInsertId()返回上次插入操作最后一条ID,但要注意:如果用insert into tb(col1,col2) values(v1,v2),(v11,v22)..的方式一次插入多条记录,lastinsertid()返回的只是第一条(v1,v2)插入时的ID,而不是最后一条记录插入的记录ID。
PDOStatement::fetch()是用来获取一条记录。配合while来遍历。
PDOStatement::fetchAll()是获取所有记录集到一个中。
PDOStatement::fetchcolumn([int column_indexnum])用于直接访问列,参数column_indexnum是该列在行中的从0开始索引值,但是,这个方法一次只能取得同一行的一列,只要执行一次,就跳到下一行。因此,用于直接访问某一列时较好用,但要遍历多列就用不上。
PDOStatement::rowcount()适用于当用query("select ...")方法时,获取记录的条数。也可以用于预处理中。$stmt->rowcount();
PDOStatement::columncount()适用于当用query("select ...")方法时,获取记录的列数。

注解:
1、选fetch还是fetchall?
小记录集时,用fetchall效率高,减少从数据库检索次数,但对于大结果集,用fetchall则给系统带来很大负担。数据库要向WEB前端传输量太大反而效率低。
2、fetch()或fetchall()有几个参数:
mixed pdostatement::fetch([int fetch_style [,int cursor_orientation [,int cursor_offset]]])
array pdostatement::fetchAll(int fetch_style)

fetch_style参数:
■$row=$rs->fetchAll(PDO::FETCH_BOTH); FETCH_BOTH是默认的,可省,返回关联和索引。
■$row=$rs->fetchAll(PDO::FETCH_ASSOC); FETCH_ASSOC参数决定返回的只有关联数组。
■$row=$rs->fetchAll(PDO::FETCH_NUM); 返回索引数组
■$row=$rs->fetchAll(PDO::FETCH_OBJ); 如果fetch()则返回对象,如果是fetchall(),返回由对象组成的二维数组

复制代码 代码如下:

$dbh = new PDO('mysql:host=localhost;dbname=access_control', 'root', ''); 
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
$dbh->exec('set names utf8');
/*添加*/
//$sql = "INSERT INTO `user` SET `login`=:login AND `password`=:password";
$sql = "INSERT INTO `user` (`login` ,`password`)VALUES (:login, :password)";  $stmt = $dbh->prepare($sql);  $stmt->execute(array(':login'=>'kevin2',':password'=>'')); 
echo $dbh->lastinsertid(); 
/*修改*/
$sql = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId"; 
$stmt = $dbh->prepare($sql); 
$stmt->execute(array(':userId'=>'7', ':password'=>'4607e782c4d86fd5364d7e4508bb10d9')); 
echo $stmt->rowCount();
/*删除*/
$sql = "DELETE FROM `user` WHERE `login` LIKE 'kevin_'"; //kevin% 
$stmt = $dbh->prepare($sql); 
$stmt->execute(); 
echo $stmt->rowCount(); 
/*查询*/
$login = 'kevin%'; 
$sql = "SELECT * FROM `user` WHERE `login` LIKE :login"; 
$stmt = $dbh->prepare($sql); 
$stmt->execute(array(':login'=>$login)); 
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){    
 print_r($row); 

print_r( $stmt->fetchAll(PDO::FETCH_ASSOC));
?>

1 建立连接

复制代码 代码如下:

   $dbh=newPDO('mysql:host=localhost;port=3306; dbname=test',$user,$pass,array(
 PDO::ATTR_PERSISTENT=>true
 ));
 ?>

持久性链接PDO::ATTR_PERSISTENT=>true

2. 捕捉错误

复制代码 代码如下:

   try{
 $dbh=newPDO('mysql:host=localhost;dbname=test',$user,$pass);
 $dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
 $dbh->exec("SET CHARACTER SET utf8");
 $dbh=null; //断开连接
 }catch(PDOException$e){
 print"Error!:".$e->getMessage()."
";
 die();
 }
 ?>

3. 事务的

复制代码 代码如下:

try{
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();//开启事务
$dbh->exec("insertintostaff(id,first,last)values(23,'Joe','Bloggs')");
$dbh->exec("insertintosalarychange(id,amount,changedate)
values(23,50000,NOW())");
$dbh->commit();//提交事务
}catch(Exception$e){
$dbh->rollBack();//错误回滚
echo"Failed:".$e->getMessage();
}
?>

4. 错误处理

a. 静默模式(默认模式)

复制代码 代码如下:

$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT); //不显示错误
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//显示警告错误,并继续执行
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//产生致命错误,PDOException

复制代码 代码如下:

   try{   
  $dbh = new PDO($dsn, $user, $password);   
  $sql = 'Select * from city where CountryCode =:country';   
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);   
  $stmt = $dbh->prepare($sql);   
  $stmt->bindParam(':country', $country, PDO::PARAM_STR);   
  $stmt->execute();   
  while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {     
   print $row['Name'] . "/t";   
  } 
 }   // if there is a problem we can handle it here 
 catch (PDOException $e)  {   
  echo 'PDO Exception Caught.  ';   
  echo 'Error with the database:
';   
  echo 'SQL Query: ', $sql;  
  echo 'Error: ' . $e->getMessage(); 
 }
 ?>

1. 使用 query()

复制代码 代码如下:

$dbh->query($sql); 当$sql 中变量可以用$dbh->quote($params); //转义字符串的数据
$sql = 'Select * from city where CountryCode ='.$dbh->quote($country); 
foreach ($dbh->query($sql) as $row)   {   
 print $row['Name'] . "/t";   
 print $row['CountryCode'] . "/t";   
 print $row['Population'] . "/n";
}
?>

2. 使用 prepare, bindParam和 execute [建议用,同时可以用添加、修改、删除]

复制代码 代码如下:

$dbh->prepare($sql); 产生了个PDOStatement对象

PDOStatement->bindParam()

PDOStatement->execute();//可以在这里放绑定的相应变量
?>

3. 事物

复制代码 代码如下:

 try { 
  $dbh = new PDO('mysql:host=localhost;dbname=test', 'root', ''); 
  $dbh->query('set names utf8;'); 
  $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
  $dbh->beginTransaction(); 
  $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('mick', 22);"); 
  $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('lily', 29);");
  $dbh->exec("Insert INTO `test`.`table` (`name` ,`age`)VALUES ('susan', 21);"); 
  $dbh->commit();
 } catch (Exception $e) { 
  $dbh->rollBack(); 
  echo "Failed: " . $e->getMessage(); 
 } 
?>

以上就是关于PHP中pdo的相关用法的全部内容了,希望本文能对大家有所帮助,也希望大家能够喜欢。

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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Two Point Museum: All Exhibits And Where To Find Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How to fix mysql_native_password not loaded errors on MySQL 8.4 How to fix mysql_native_password not loaded errors on MySQL 8.4 Dec 09, 2024 am 11:42 AM

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Top 10 PHP CMS Platforms For Developers in 2024 Top 10 PHP CMS Platforms For Developers in 2024 Dec 05, 2024 am 10:29 AM

CMS stands for Content Management System. It is a software application or platform that enables users to create, manage, and modify digital content without requiring advanced technical knowledge. CMS allows users to easily create and organize content

How to Add Elements to the End of an Array in PHP How to Add Elements to the End of an Array in PHP Feb 07, 2025 am 11:17 AM

Arrays are linear data structures used to process data in programming. Sometimes when we are processing arrays we need to add new elements to the existing array. In this article, we will discuss several ways to add elements to the end of an array in PHP, with code examples, output, and time and space complexity analysis for each method. Here are the different ways to add elements to an array: Use square brackets [] In PHP, the way to add elements to the end of an array is to use square brackets []. This syntax only works in cases where we want to add only a single element. The following is the syntax: $array[] = value; Example

See all articles