Simple use of php pdo (1)
Introduction:
PDO extension defines a lightweight, consistent interface for PHP to access databases. It provides a data access abstraction layer so that no matter what database is used, queries and retrieve data.
It provides a database access abstraction layer that allows us to operate different databases through consistent functions and writing methods, which is beneficial to future database migrations and of course also improves security.
Comparison:
Commonly used methods for php operating databases, taking mysql as an example, include php_mysql, php_mysqli, pdo
1.php_mysql and php_mysqli are not portable and can only be applied to mysql databases, while pdo can be easily transplanted .
2.php_mysql is a function that we learn to operate the database when we are new to PHP, but in fact it is rarely used. The most important point is that it can easily cause security problems.
There is SQL injection, so PHP provides the function mysql_real_escape_string. If there are many variables, each one must go through mysql_real_escape_string
Instead it becomes very troublesome.
3.pdo supports preprocessing. The preprocessing function can effectively avoid SQL injection and improve efficiency.
4.php_mysqli and pdo both support object-oriented.
5.pdo The long connection method has better performance than php_mysqli (refer to online information)
php_mysql method has little advantage. The most fatal thing about php_mysqli is that it cannot be transplanted to other databases unless you are sure that you will not change the database. . Obviously the pdo method of connecting to the database will be a trend.
pdo simple operation of the database:
First of all, php needs to enable php-pdo related extensions
<?php $dbType = 'mysql'; $dbUser = 'root'; $dbPass = 'simael'; $dbhost = 'localhost'; $dbName = 'pdotest'; $dsn="$dbType:host=$dbhost;dbname=$dbName"; try{ $pdo = new PDO($dsn, $dbUser, $dbPass); echo "PDO成功连接MySQL数据库!"; }catch(PDOException $exception){ echo $exception->getMessage(); }
Insert data
<?php //$pdo->query('set names utf8'); $sql = "INSERT INTO la_comments SET nick_name='formPdo',email='pdo@pdo.com',comment='中文comment',page_id='11',created_at=NOW(),updated_at=NOW()"; $res1 = $pdo->exec($sql); var_dump($res1);
At this time, when I go to the database, I see that the Chinese characters may be garbled, because of encoding problems. The reason
adding code
$pdo->query('set names utf8');
The coding issues summarized online that need to be paid attention to are as follows:
1. Server program declares encoding. For example, header("Content-type: text/html; charset=utf-8");
2. The client declares the encoding, such as
3. Database encoding, table and field encoding
4. Encoding properties of the file itself
5. Please declare the encoding when connecting to the database, such as $pdo->query('set names utf8');
As long as the above are consistent, the encoding problem will generally be solved.
Full sample code: (the file itself should also be encoded in utf8)
$dbType = 'mysql'; $dbUser = 'root'; $dbPass = 'simael'; $dbhost = 'localhost'; $dbName = 'pdotest'; $dsn="$dbType:host=$dbhost;dbname=$dbName"; try{ $pdo = new PDO($dsn, $dbUser, $dbPass,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES'utf8';")); //$pdo = new PDO($dsn, $dbUser, $dbPass); echo "PDO成功连接MySQL数据库!"; }catch(PDOException $exception){ echo $exception->getMessage(); } $pdo->query('set names utf8'); $sql = "INSERT INTO la_comments SET nick_name='formPdo',email='pdo@pdo.com',comment='中文comment',page_id='11',created_at=NOW(),updated_at=NOW()"; $res1 = $pdo->exec($sql); var_dump($res1); $sql = "SELECT * FROM la_comments"; $res2 = $pdo->query($sql); while($row = $res2->fetch()){ print_r($row); echo '
'; } $pdo = null; ?>
The above introduces the simple use of php pdo (1), including the content. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











MySQL and phpMyAdmin can be effectively managed through the following steps: 1. Create and delete database: Just click in phpMyAdmin to complete. 2. Manage tables: You can create tables, modify structures, and add indexes. 3. Data operation: Supports inserting, updating, deleting data and executing SQL queries. 4. Import and export data: Supports SQL, CSV, XML and other formats. 5. Optimization and monitoring: Use the OPTIMIZETABLE command to optimize tables and use query analyzers and monitoring tools to solve performance problems.

AI can help optimize the use of Composer. Specific methods include: 1. Dependency management optimization: AI analyzes dependencies, recommends the best version combination, and reduces conflicts. 2. Automated code generation: AI generates composer.json files that conform to best practices. 3. Improve code quality: AI detects potential problems, provides optimization suggestions, and improves code quality. These methods are implemented through machine learning and natural language processing technologies to help developers improve efficiency and code quality.

In MySQL, add fields using ALTERTABLEtable_nameADDCOLUMNnew_columnVARCHAR(255)AFTERexisting_column, delete fields using ALTERTABLEtable_nameDROPCOLUMNcolumn_to_drop. When adding fields, you need to specify a location to optimize query performance and data structure; before deleting fields, you need to confirm that the operation is irreversible; modifying table structure using online DDL, backup data, test environment, and low-load time periods is performance optimization and best practice.

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

To safely and thoroughly uninstall MySQL and clean all residual files, follow the following steps: 1. Stop MySQL service; 2. Uninstall MySQL packages; 3. Clean configuration files and data directories; 4. Verify that the uninstallation is thorough.

Efficient methods for batch inserting data in MySQL include: 1. Using INSERTINTO...VALUES syntax, 2. Using LOADDATAINFILE command, 3. Using transaction processing, 4. Adjust batch size, 5. Disable indexing, 6. Using INSERTIGNORE or INSERT...ONDUPLICATEKEYUPDATE, these methods can significantly improve database operation efficiency.

MySQL functions can be used for data processing and calculation. 1. Basic usage includes string processing, date calculation and mathematical operations. 2. Advanced usage involves combining multiple functions to implement complex operations. 3. Performance optimization requires avoiding the use of functions in the WHERE clause and using GROUPBY and temporary tables.

Methods for configuring character sets and collations in MySQL include: 1. Setting the character sets and collations at the server level: SETNAMES'utf8'; SETCHARACTERSETutf8; SETCOLLATION_CONNECTION='utf8_general_ci'; 2. Create a database that uses specific character sets and collations: CREATEDATABASEexample_dbCHARACTERSETutf8COLLATEutf8_general_ci; 3. Specify character sets and collations when creating a table: CREATETABLEexample_table(idINT
