search
HomeBackend DevelopmentPHP TutorialSimple 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 = &#39;mysql&#39;;
$dbUser = &#39;root&#39;;
$dbPass = &#39;simael&#39;;
$dbhost = &#39;localhost&#39;;
$dbName = &#39;pdotest&#39;;
$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');
data storage still has errors is because it is possible that your header is gbk encoded

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.

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
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

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.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.