search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the use of PDO, the mysql connection method in PHP, pdo Huan Chuan Rong Xuan﹁В_PHP tutorial

Detailed explanation of the use of PDO, the mysql connection method in php, pdo Huan Chuan Rong Xuan﹁В

Common methods of PDO:

PDO::query() is mainly used for operations that return recorded results (PDOStatement), especially select operations.

PDO::exec() is mainly for operations that do not return a result set. Such as insert, update and other operations. Returns the number of affected rows.
PDO::lastInsertId() returns the last ID of the last insertion operation, but please note: if you use insert into tb(col1,col2) values(v1,v2),(v11,v22).. to insert multiple records at one time , lastinsertid() returns only the ID of the first (v1, v2) insert, not the record ID of the last record inserted.
PDOStatement::fetch() is used to obtain a record. Use while to traverse.
PDOStatement::fetchAll() fetches all records into one.
PDOStatement::fetchcolumn([int column_indexnum]) is used to directly access the column. The parameter column_indexnum is the index value of the column in the row starting from 0. However, this method can only obtain one column of the same row at a time. As long as it is executed once, it will jump. Go to the next line. Therefore, it is easier to use when directly accessing a certain column, but it is not useful when traversing multiple columns.
PDOStatement::rowcount() is suitable for obtaining the number of records when using the query("select...") method. Can also be used in preprocessing. $stmt->rowcount();
PDOStatement::columncount() is suitable for obtaining the number of columns in a record when using the query("select...") method.

Note:
1. Choose fetch or fetchall?
When the record set is small, using fetchall is more efficient and reduces the number of retrieval times from the database. However, for large result sets, using fetchall brings a lot of burden to the system. The amount of data the database needs to transmit to the WEB front-end is too large and inefficient.
2. fetch() or fetchall() has several parameters:
mixed pdostatement::fetch([int fetch_style [,int cursor_orientation [,int cursor_offset]]])
array pdostatement::fetchAll(int fetch_style)

fetch_style parameter:
■$row=$rs->fetchAll(PDO::FETCH_BOTH); FETCH_BOTH is the default, can be omitted, and returns the association and index.
■$row=$rs->fetchAll(PDO::FETCH_ASSOC); The FETCH_ASSOC parameter determines that only associative arrays are returned.
■$row=$rs->fetchAll(PDO::FETCH_NUM); returns index array
■$row=$rs->fetchAll(PDO::FETCH_OBJ); If fetch() returns an object, if fetchall() returns a two-dimensional array composed of objects

Copy code The code is as follows:

$dbh = new PDO('mysql:host=localhost;dbname=access_control', 'root', '');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->exec('set names utf8');
/*Add*/
//$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();
/*Modify*/
$sql = "UPDATE `user` SET `password`=:password WHERE `user_id`=:userId";
$stmt = $dbh->prepare($sql);
$stmt->execute(array(':userId'=>'7', ':password'=>'4607e782c4d86fd5364d7e4508bb10d9'));
echo $stmt->rowCount();
/*Delete*/
$sql = "DELETE FROM `user` WHERE `login` LIKE 'kevin_'"; //kevin%
$stmt = $dbh->prepare($sql);
$stmt->execute();
echo $stmt->rowCount();
/*Query*/
$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 Establish connection

Copy code The code is as follows:

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

Persistence link PDO::ATTR_PERSISTENT=>true

2. Catching errors

Copy code The code is as follows:

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; //Disconnect
}catch(PDOException$e){
print"Error!:".$e->getMessage()."
";
die();
}
?>

3. Business

Copy code The code is as follows:

try{
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbh->beginTransaction();//Open transaction
$dbh->exec("insertintostaff(id,first,last)values(23,'Joe','Bloggs')");
$dbh->exec("insertintosalarychange(id,amount,changedate)
values(23,50000,NOW())");
$dbh->commit();//Submit transaction
}catch(Exception$e){
$dbh->rollBack();//Error rollback
echo"Failed:".$e->getMessage();
}
?>

4. Error handling

a. Silent mode (default mode)

Copy code The code is as follows:

$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT); //Do not display errors
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);//Display warning errors and continue execution
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);//A fatal error occurs, PDOException

Copy code The code is as follows:

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. Use query()

Copy code The code is as follows:

$dbh->query($sql); When variables in $sql can be used $dbh->quote($params); //Escape string data
$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. Use prepare, bindParam and execute [recommended, you can also add, modify, delete]

Copy code The code is as follows:

$dbh->prepare($sql); generates a PDOStatement object

PDOStatement->bindParam()

PDOStatement->execute();//You can put the corresponding bound variables here
?>

3. Things

Copy code The code is as follows:

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

The above is all about the usage of pdo in PHP. I hope this article can be helpful to everyone, and I hope everyone likes it.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/960715.htmlTechArticleDetailed explanation of the use of PDO in mysql connection method in php, pdo Huan Chuan敤璇﹁В Common methods of PDO: PDO::query () is mainly used for operations that return recorded results (PDOStatement), especially select operations. ...
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

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor