search
Homephp教程php手册php使用PDO操作MySQL数据库实例

这篇文章主要介绍了php使用PDO操作MySQL数据库,实例分析了PDO的开启与针对MySQL数据库的增删改查等基本操作方法,具有一定参考借鉴价值,需要的朋友可以参考下

本文实例讲述了php使用PDO操作MySQL数据库的方法。分享给大家供大家参考。具体分析如下:

PDO是mysql数据库操作的一个公用类,我们不需要进行自定类就可以直接使用pdo来操作数据库,但是在php默认配置中pdo是未开启所以我们必须先在php.ini中开启它才可以使用,这里来详细介绍一下.

PDO扩展为PHP访问数据库定义了一个轻量级的,一致性的接口,它提供了一个数据访问抽象层,这样,无论使用什么数据库,都可以通过一致的函数执行查询和获取数据.

PDO支持的PHP版本为PHP5.1以及更高的版本,而且在PHP5.2下PDO默认为开启状态.

下面是在php.ini中PDO的配置:

复制代码 代码如下:

extension=php_pdo.dll

为了启用对某个数据库的支持,需要在php配置文件中将相应的扩展打开,例如要支持MySQL,需要开启下面的扩展:

复制代码 代码如下:

extension=php_pdo_mysql.dll

这里是使用PDO对mysql进行基本的增删改查操作,PHP程序代码如下:

复制代码 代码如下:

header("content-type:text/html;charset=utf-8");
$dsn="mysql:dbname=test;host=localhost";
$db_user='root';
$db_pass='admin';
try{
 $pdo=new PDO($dsn,$db_user,$db_pass);
}catch(PDOException $e){
 echo '数据库连接失败'.$e->getMessage();
}
//新增
$sql="insert into buyer (username,password,email) values ('ff','123456','admin@admin.com')";
$res=$pdo->exec($sql);
echo '影响行数:'.$res;
 
//修改
$sql="update buyer set username='ff123' where id>3";
$res=$pdo->exec($sql);
echo '影响行数:'.$res;
//查询
$sql="select * from buyer";
$res=$pdo->query($sql);
foreach($res as $row){
 echo $row['username'].'
';
}
//删除
$sql="delete from buyer where id>5";
$res=$pdo->exec($sql);
echo '影响行数:'.$res;

希望本文所述对大家的php程序设计有所帮助。

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

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 Tools

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool