search
HomeBackend DevelopmentPHP Tutorial001 - Detailed analysis of PDO usage

001 - Detailed analysis of PDO usage

Apr 08, 2018 pm 02:35 PM
usageparsedetailed

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() );  //获取全部常量


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
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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software