Home Backend Development PHP Tutorial 001 - Detailed analysis of PDO usage

001 - Detailed analysis of PDO usage

Apr 08, 2018 pm 02:35 PM
usage parse detailed

The content introduced in this article is a detailed analysis of PDO usage, and I will share it with you now. Friends in need can refer to

《PDO》
41、作用 :能够解决用户在需要使用不同的数据库的时候进行来回的切换,PDO能够自动的进行数据库的切换。
42、使用PDO	
    a)Php.ini文件找开启PDO扩展
43、使用PDO操作数据库基本步骤	
    a)连接认证		
        i.$pdo = new PDO(“mysql:host=localhost;port=3306;dbname=project”,”root”,”root”);			
            ii.dbname 是进入的数据库	
    b)组织SQL语句		
        i.$sql = “show tables”;	
    c)发送SQL语句,接收执行结果		
        i.$stmt = $pdo->query( $sql );	
    d)从结果集中获取数据		
        i.$stmt->fetch();
44、PDO常用函数	
    a)stdClass		标准类 空类	
    b)PDO:		
        i.exec( $sql );				执行SQL语句,返回受影响的行数		(用于 增删改)		
        ii.$stmt = query( $sql );		执行SQL语句,返回PDOStatement对象	(用于 查)	
    c)PDOStatement(结果集)		
        i.$stmt->fetch( );			返回一个关联数组+索引数组的集合			
            1.参1		PDO::FETCH_ASSOC		只返回关联数组			
            2.参2		PDO::FETCH_NUM			只返回索引数组		
        ii.$stmt->fetchAll()			获取结果集所有内容(参数同fetch())		
        iii.返回一个对象Object			
            1.class Persion{		}			
            2.$stmt->fetchObject( Persion)		
        iv.bindColumn 和 fetch	绑定一列到一个变量			
            1.$stmt->bindColumn(‘s_name’,$name);			
            2.$stmt->bindColumn( 3 ,$number);    //注意:索引从1开始			
            3.$stmt->fetch( );			
            4.echo $name,$number	
    d)PDO预处理		
        i.:s_name  这些 可以全用 ? 号代替(绑定数据时 就用索引值);		
        ii.使用数组指定预处理变量			
            1.步骤:				
                a)$sql = “insert into pro_student values(null,:s_name,:s_num,:s_gender,:s_age,:c_id)”;	//sql				
                b)$stmt = $pdo->prepare( $sql );	//发送预处理				
                c)给预处理绑定数据					
                    i.$arr = array(					
                    ii.   ‘:s_name’=>’房祖名’,					
                    iii.   ‘:s_num’=>’itcast0001’,
                    iv.   ‘:s_gender’=>’男’,
                    v.   ‘:s_age’=>’28’,		
                    vi.   ‘:c_id’=>’2’,					
                    vii.)				
                d)$stmt->execute( $arr );		//执行预处理		
        iii.通过绑定变量的形式			
            1.步骤				
                a)$sql = “insert into pro_student values(null,:s_name,:s_num,:s_gender,:s_age,:c_id)”;	//sql				
                b)$stmt = $pdo->prepare( $sql );	//发送预处理				
                c)给预处理绑定数据					
                    i.$name = “李莫愁”;					
                    ii.$num= “itcast0002”;					
                    iii.$gender = “女”;					
                    iv.$age = “30”;					
                    v.$c_id = “3”;					
                    vi.//将变量绑定给预处理					
                    vii.$stmt->bindParam(‘:s_name’,$name);					
                    viii.$stmt->bindParam(‘:s_num’,$num);					
                    ix.$stmt->bindParam(‘:s_gender’,$gender);					
                    x.$stmt->bindParam(‘:s_age’,$age);					
                    xi.$stmt->bindParam(‘:c_id’,$c_id);				
                d)$stmt->execute(  );		//执行预处理	
    e)PDO事务处理		
        i.事务处理就是  增删改		
        ii.注意:数据表的存储引擎必须是 innoDB		
        iii.事务处理流程			
            1.$pdo = new PDO(‘mysql:host=localhost;port=3306;dbname=project’,’root’,’root’);	//连接认证			
            2.$res = $pdo->beginTransaction();		//开启事务			
            3.事务处理				
                a)$sql = “updata pro_student set s_age=28 where s_id=20”;				
                b)$lines = $pdo->exec( $sql );	//返回受影响的行数				
                c)$sql = “select * from pro_student where s_id=20”;				
                d)$stmt = $pdo->query( $sql );				
                e)$stmt->fetch(PDO::FETCH_ASSOC);			
            4.提交事务				
                a)if( $links ){				
                b)    $pdo->commit();	//更新成功				
                c)}else{				
                d)    $pdo->rollBack();	//更新失败   回滚数据				
                e)}	
    f)PDO 属性设置		
        i.设置PDO在处理数据的过程中采用什么方式去处理		
        ii.PDO::getAttribute();		//获取属性		
        iii.PDO::setAttribute();		//设置属性		
        iv.示例:			
            1.$pdo = new PD(‘mysql:host=localhost;port=3306;dbname=project’,’root’,’root’);	//连接认证			
	    2.$peo->getAttrbute(PDO::ATTR_AUTOCOMMIT);		//获取 自动提交属性			
	    3.$pdo->setAttrbute(PDO::ATTR_AUTOCOMMIT,0)		//设置 关闭自动提交		
        v.参数记忆:			
            1.PDO::ATTR_CASE	强制列名为指定的大小写				
                a)PDO::CASE_LOWER		强制小写				
		b)PDO::CASE_UPPER		强制大写	
	vi...... 更多请参考手册 ......
    g)PDO异常处理		
	i.try{		
	ii.    //设置错误处理模式(必须设置才能生效)		
	iii.    $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);		
	iv.    //一旦出错立即进入catch语句		
	v.}catch(PDOException $e){		
	vi.    $e->getTrace();  //获取完整的错误数据		
	vii.    $e->getFile();   //获取错误文件		
	viii.   $e->getLine();   //获取错误行号		
	ix.    $e->getMessage();   //获取错误原因		
	x.}	
    h)反射:		
	i.反射就是将其他类的结构给反应出来,从而可以对类的结构进行了解便于对类的使用		
	ii.Reflection		
	iii.reflectionClass::export(要反射的类名)		
	iv.调用reflectionClass的静态方法		
	v.var_dump( reflectionClass::export(‘PDO’) );		
	vi		
	vii.$rc = new ReflectionClass(‘PDO’);  //创建ReflectionClass对象		
	viii.var_dump( $rc->getProperties() );  //获取全部属性		
	ix.var_dump( $rc->getMothods() );   //获取全部方法		
	x.var_dump( $rc->getConstants() );  //获取全部常量
Copy after login


The above is the detailed content of 001 - Detailed analysis of PDO usage. For more information, please follow other related articles on the PHP Chinese website!

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks 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)

Detailed explanation of Oracle error 3114: How to solve it quickly Detailed explanation of Oracle error 3114: How to solve it quickly Mar 08, 2024 pm 02:42 PM

Detailed explanation of Oracle error 3114: How to solve it quickly, specific code examples are needed. During the development and management of Oracle database, we often encounter various errors, among which error 3114 is a relatively common problem. Error 3114 usually indicates a problem with the database connection, which may be caused by network failure, database service stop, or incorrect connection string settings. This article will explain in detail the cause of error 3114 and how to quickly solve this problem, and attach the specific code

Usage of WPSdatedif function Usage of WPSdatedif function Feb 20, 2024 pm 10:27 PM

WPS is a commonly used office software suite, and the WPS table function is widely used for data processing and calculations. In the WPS table, there is a very useful function, the DATEDIF function, which is used to calculate the time difference between two dates. The DATEDIF function is the abbreviation of the English word DateDifference. Its syntax is as follows: DATEDIF(start_date,end_date,unit) where start_date represents the starting date.

Analysis of the meaning and usage of midpoint in PHP Analysis of the meaning and usage of midpoint in PHP Mar 27, 2024 pm 08:57 PM

[Analysis of the meaning and usage of midpoint in PHP] In PHP, midpoint (.) is a commonly used operator used to connect two strings or properties or methods of objects. In this article, we’ll take a deep dive into the meaning and usage of midpoints in PHP, illustrating them with concrete code examples. 1. Connect string midpoint operator. The most common usage in PHP is to connect two strings. By placing . between two strings, you can splice them together to form a new string. $string1=&qu

Parsing Wormhole NTT: an open framework for any Token Parsing Wormhole NTT: an open framework for any Token Mar 05, 2024 pm 12:46 PM

Wormhole is a leader in blockchain interoperability, focused on creating resilient, future-proof decentralized systems that prioritize ownership, control, and permissionless innovation. The foundation of this vision is a commitment to technical expertise, ethical principles, and community alignment to redefine the interoperability landscape with simplicity, clarity, and a broad suite of multi-chain solutions. With the rise of zero-knowledge proofs, scaling solutions, and feature-rich token standards, blockchains are becoming more powerful and interoperability is becoming increasingly important. In this innovative application environment, novel governance systems and practical capabilities bring unprecedented opportunities to assets across the network. Protocol builders are now grappling with how to operate in this emerging multi-chain

Detailed explanation and usage introduction of MySQL ISNULL function Detailed explanation and usage introduction of MySQL ISNULL function Mar 01, 2024 pm 05:24 PM

The ISNULL() function in MySQL is a function used to determine whether a specified expression or column is NULL. It returns a Boolean value, 1 if the expression is NULL, 0 otherwise. The ISNULL() function can be used in the SELECT statement or for conditional judgment in the WHERE clause. 1. The basic syntax of the ISNULL() function: ISNULL(expression) where expression is the expression to determine whether it is NULL or

Analysis of new features of Win11: How to skip logging in to Microsoft account Analysis of new features of Win11: How to skip logging in to Microsoft account Mar 27, 2024 pm 05:24 PM

Analysis of new features of Win11: How to skip logging in to a Microsoft account. With the release of Windows 11, many users have found that it brings more convenience and new features. However, some users may not like having their system tied to a Microsoft account and wish to skip this step. This article will introduce some methods to help users skip logging in to a Microsoft account in Windows 11 and achieve a more private and autonomous experience. First, let’s understand why some users are reluctant to log in to their Microsoft account. On the one hand, some users worry that they

Apache2 cannot correctly parse PHP files Apache2 cannot correctly parse PHP files Mar 08, 2024 am 11:09 AM

Due to space limitations, the following is a brief article: Apache2 is a commonly used web server software, and PHP is a widely used server-side scripting language. In the process of building a website, sometimes you encounter the problem that Apache2 cannot correctly parse the PHP file, causing the PHP code to fail to execute. This problem is usually caused by Apache2 not configuring the PHP module correctly, or the PHP module being incompatible with the version of Apache2. There are generally two ways to solve this problem, one is

Use CSS Transform to transform elements Use CSS Transform to transform elements Feb 24, 2024 am 10:09 AM

Usage of Transform in CSS The Transform property of CSS is a very powerful tool that can perform operations such as translation, rotation, scaling and tilting of HTML elements. It can dramatically change the appearance of elements and make web pages more creative and dynamic. In this article, we will introduce the various uses of Transform in detail and provide specific code examples. 1. Translate (Translate) Translate refers to moving an element a specified distance along the x-axis and y-axis. Its syntax is as follows: tran

See all articles