Home > Article > Backend Development > Use PDO to operate MySQL database
The content of this article is about using PDO to operate MySQL database. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
Create the database first. Copy the code to the TXT file, then save it as 'Create database.txt' and finally modify it to 'Create database.sql', and finally use navicat to run the database file. The database is created.
The code is as follows:
CREATE TABLE `user` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(25) NOT NULL DEFAULT '', `gender` tinyint(1) NOT NULL DEFAULT '1', `age` int(11) NOT NULL DEFAULT '0', `flag` tinyint(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=11 DEFAULT CHARSET=utf8; /*Data for the table `user` */ insert into `user`(`id`,`name`,`gender`,`age`,`flag`) values (1,'allen',1,20,1),(2,'alice',2,18,1),(3,'bob',1,21,1),(4,'dave',1,25,1),(5,'eve',2,20,1),(6,'joy',1,21,1),(7,'june',1,23,1),(8,'linda',2,22,1),(9,'lisa',2,22,1),(10,'liz',2,23,1);
Then create a new PHP file. pdo.php
<?php $db = array( 'host' => '127.0.0.1', //设置服务器地址 'port' => '3306', //设端口 'dbname' => 'test', //设置数据库名 'username' => 'root', //设置账号 'password' => 'yangji0321', //设置密码 'charset' => 'utf8', //设置编码格式 'dsn' => 'mysql:host=127.0.0.1;dbname=test;port=3306;charset=utf8', //这里不知道为什么,也需要这样再写一遍。 ); //连接 $options = array( PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, //默认是PDO::ERRMODE_SILENT, 0, (忽略错误模式) PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, // 默认是PDO::FETCH_BOTH, 4 ); try{ $pdo = new PDO($db['dsn'], $db['username'], $db['password'], $options); }catch(PDOException $e){ die('数据库连接失败:' . $e->getMessage()); } //或者更通用的设置属性方式: //$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //设置异常处理方式 //$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); //设置默认关联索引遍历 echo '<pre/>'; //1 查询 //1)使用query $stmt = $pdo->query('select * from user limit 2'); //返回一个PDOStatement对象 //$row = $stmt->fetch(); //从结果集中获取下一行,用于while循环 $rows = $stmt->fetchAll(); //获取所有 $row_count = $stmt->rowCount(); //记录数,2 print_r($rows); echo '<br>'; //2)使用prepare 推荐! $stmt = $pdo->prepare("select * from user where name = ? and age = ? "); $stmt->bindValue(1,'allen'); $stmt->bindValue(2,20); $stmt->execute(); //执行一条预处理语句 .成功时返回 TRUE, 失败时返回 FALSE $rows = $stmt->fetchAll(); $row_count = $stmt->rowCount(); //记录数,2 print_r($rows); print_r($row_count); echo '<br>'; //2 新增、更新、删除 //A.1)普通操作 //$count = $pdo->exec("insert into user(name,gender,age)values('test',2,23)"); //返回受影响的行数 //echo $pdo->lastInsertId(); //$count = $pdo->exec("update user set name='test2' where id = 15"); //返回受影响的行数 //$count = $pdo->exec("delete from user where id = 15"); //返回受影响的行数 //A.2)使用prepare 推荐! $stmt = $pdo->prepare("insert into user(name,gender,age)values(?,?,?)"); $stmt->bindValue(1, 'test'); $stmt->bindValue(2, 2); $stmt->bindValue(3, 23); $stmt->execute(); $count = $stmt->rowCount();//受影响行数 echo 'prepare方法影响行数:'.$count; echo '<br>'; //A.3)使用prepare 批量新增 $stmt = $pdo->prepare("insert into user(name,gender,age)values(?,?,?)"); $stmt->bindParam(1, $name); $stmt->bindParam(2, $gender); $stmt->bindParam(3, $age); $data = array( array('t1', 1, 22), array('t2', 2, 23), ); foreach ($data as $vo){ list($name, $gender, $age) = $vo; $stmt->execute(); } //B)更新操作 echo '<br>'; $stmt = $pdo->prepare("UPDATE `user` SET `age`=? WHERE (`name`= ? )"); $stmt->bindValue(1, '20'); $stmt->bindValue(2, 'allen'); $num = $stmt->execute(); $count = $stmt->rowCount();//受影响行数 echo '更新操作影响行数:'.$count; //删除操作 $stmt = $pdo->prepare("DELETE FROM `user` WHERE (`name`= ? )"); $stmt->bindValue(1, 't1'); $num = $stmt->execute(); $count = $stmt->rowCount();//受影响行数 echo '删除操作影响行数:'.$count; # 【示例5:统计数据】:统计company表有多少条数据 echo '<br>'; $num = $pdo->query("select count(*) from user"); $count = $num->fetchColumn(); echo '共有数据:【'.$count.'】条'; ?> pdo::query()方法 当执行返回结果集的select查询时,或者所影响的行数无关紧要时,应当使用pdo对象中的query()方法. 如果该方法成功执行指定的查询,则返回一个PDOStatement对象. 如果使用了query()方法,并想了解获取数据行总数,可以使用PDOStatement对象中的rowCount()方法获取. pdo::exec()方法 当执行insert,update,delete没有结果集的查询时,使用pdo对象中的exec()方法去执行. 该方法成功执行时,将返回受影响的行数.注意,该方法不能用于select查询. PDO事务: $pdo->beginTransaction();//开启事务处理 try{ //PDO预处理以及执行语句... $pdo->commit();//提交事务 }catch(PDOException $e){ $pdo->rollBack();//事务回滚 //相关错误处理 throw $e; }
Related recommendations:
PHP database is based on PDO operation class (mysql)
PDO queries one row at a time data
The above is the detailed content of Use PDO to operate MySQL database. For more information, please follow other related articles on the PHP Chinese website!