PHP操作MYSQL--PDO
感觉比直接弄SQL语句高级,但还不到ORM的封装。
一步一步进化。
app.json
{
"db": {
"user": "root",
"password": "xxxx",
"host": "10.2.3.4",
"port": "3306",
"dbname": "bookstore"
}
}
config.php
<?php
namespace Bookstore\Utils;
use Bookstore\Exceptions\NotFoundException;
require_once __DIR__ . '/NotFoundException.php';
class Config {
private $data;
//类静态变量,保证变量唯一性
private static $instance;
//构造函数私有化,类外部不可以调用.
private function __construct() {
$json = file_get_contents(__DIR__ . '/app.json');
$this->data = json_decode($json, true);
}
//单例模式,保证只实例化一个类.
public static function getInstance() {
if (self::$instance == null) {
//是可以自己实例化自己的.
self::$instance = new Config();
}
return self::$instance;
}
public function get($key) {
if (!isset($this->data[$key])) {
throw new NotFoundException("Key $key not in config.");
}
return $this->data[$key];
}
}
?>
test.php
<?php
//使用命名空间,易于在大型应用中管理和组织php类.
use Bookstore\Utils\Config;
//命名空间可以直接use,但如果这个命名空间没有在标准约定位置,且没有自动载入的话,需要使用require来手工定位一下.
require_once __DIR__ . '\Config.php';
header("content-type:text/html;charset=utf-8");
$dbConfig = Config::getInstance()->get("db");
$connStr = "mysql:host={$dbConfig['host']};port={$dbConfig['port']};dbname={$dbConfig['dbname']};charset=utf8";
$db = new \PDO($connStr, $dbConfig['user'], $dbConfig['password']);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
$query = 'SELECT * FROM book WHERE author = :author';
$statement = $db->prepare($query);
$statement->bindValue('author', 'George Orwell');
$statement->execute();
$rows = $statement->fetchAll();
foreach ($rows as $row) {
var_dump($row);
}
echo "<br/>";
$query = <<<SQL
INSERT INTO book(isbn, title, author, price)
VALUES(:isbn, :title, :author, :price)
SQL;
$statement = $db->prepare($query);
$params = [
'isbn' => '9781413108614',
'title' => 'Iliad',
'author' => 'Homer',
'price' => 9.25
];
$statement->execute($params);
$result = $db->exec($query);
echo $db->lastInsertId();
echo "<br/>";
function addBook(int $id, int $amount=1):void {
$query = 'UPDATE book SET stock = stock + :n WHERE id = :id';
$statement = $db->prepare($query);
$statement->bindValue('id', $id);
$statement->bindValue('n', $amount);
if (!$statement->execute()) {
throw new Exception($statement->errorInfo()[2]);
}
}
function addSale($db, int $userId, array $bookIds):void {
$db->beginTransaction();
try {
$query = 'INSERT INTO sale(customer_id, date)'
. 'VALUES(:id, NOW())';
$statement = $db->prepare($query);
if (!$statement->execute(['id'=> $userId])) {
throw new Exception($statement->errorInfo()[2]);
}
$saleId = $db->lastInsertId();
$query = 'INSERT INTO sale_book(book_id, sale_id)'
. 'VALUES(:book, :sale)';
$statement = $db->prepare($query);
$statement->bindValue('sale', $saleId);
foreach ($bookIds as $bookId) {
$statement->bindValue('book', $bookId);
if (!$statement->execute()) {
throw new Exception($statement->errorInfo()[2]);
}
}
$db->commit();
} catch (Exception $e) {
$db->rollback();
throw $e;
}
}
try {
addSale($db, 1, [1, 2, 300]);
} catch (Exception $e) {
echo 'Error adding sale: ' . $e->getMessage();
}
try {
addSale($db, 1, [1, 2, 3]);
} catch (Exception $e) {
echo 'Error adding sale: ' . $e->getMessage();
}
?>
输出
array(6) { ["id"]=> string(1) "1" ["isbn"]=> string(13) "9780882339726" ["title"]=> string(4) "1984" ["author"]=> string(13) "George Orwell" ["stock"]=> string(2) "12" ["price"]=> string(3) "8.7" } array(6) { ["id"]=> string(1) "3" ["isbn"]=> string(13) "9780736692427" ["title"]=> string(11) "Animal Farm" ["author"]=> string(13) "George Orwell" ["stock"]=> string(1) "8" ["price"]=> string(4) "4.06" }
0
Error adding sale: Cannot add or update a child row: a foreign key constraint fails (`bookstore`.`sale_book`, CONSTRAINT `sale_book_ibfk_2` FOREIGN KEY (`book_id`) REFERENCES `book` (`id`))
PHP操作MYSQL--PDO的更多相关文章
- MySQL原生API、MySQLi面向过程、MySQLi面向对象、PDO操作MySQL
[转载]http://www.cnblogs.com/52fhy/p/5352304.html 本文将举详细例子向大家展示PHP是如何使用MySQL原生API.MySQLi面向过程.MySQLi面向对 ...
- php笔记08:数据库编程---使用php的MySQL扩展库操作MySQL数据库
1.使用php的MySQL扩展库操作MySQL数据库: php有3种方式操作MySQL数据库 (1)mysql扩展库 (2)mysqli扩展库 (3)pdo mysql扩展库与mysql数据库 ...
- php mysql PDO使用
<?php $dbh = new PDO('mysql:host=localhost;dbname=access_control', 'root', ''); $dbh->setAttri ...
- ASP.NET Core 1.0 使用 Dapper 操作 MySql(包含事务)
操作 MySql 数据库使用MySql.Data程序包(MySql 开发,其他第三方可能会有些问题). project.json 代码: { "version": "1. ...
- Python(九) Python 操作 MySQL 之 pysql 与 SQLAchemy
本文针对 Python 操作 MySQL 主要使用的两种方式讲解: 原生模块 pymsql ORM框架 SQLAchemy 本章内容: pymsql 执行 sql 增\删\改\查 语句 pymsql ...
- EF操作MySql
EF的CodeFrist操作MySql的提前准备: 1.安装两个包:MySql.Data和MySql.Data.Entity,在VS中程序包管理器中添加2个包.(备注需要的VS2015,并且EF6支持 ...
- .NET Core 使用Dapper 操作MySQL
MySQL官方驱动:http://www.cnblogs.com/linezero/p/5806814.html .NET Core 使用Dapper 操作MySQL 数据库, .NET Core 使 ...
- asp.net core 1.1 升级后,操作mysql出错的解决办法。
遇到问题 core的版本从1.0升级到1.1,操作mysql数据库,查询数据时遇到MissingMethodException问题,更新.插入操作没有问题. 如果你也遇到这个问题,请参照以下步骤进行升 ...
- 练习:python 操作Mysql 实现登录验证 用户权限管理
python 操作Mysql 实现登录验证 用户权限管理
- Python操作MySQL
本篇对于Python操作MySQL主要使用两种方式: 原生模块 pymsql ORM框架 SQLAchemy pymsql pymsql是Python中操作MySQL的模块,其使用方法和MySQLdb ...
随机推荐
- 每日一问:谈谈对 MeasureSpec 的理解
作为一名 Android 开发,正常情况下对 View 的绘制机制基本还是耳熟能详的,尤其对于经常需要自定义 View 实现一些特殊效果的同学. 网上也出现了大量的 Blog 讲 View 的 onM ...
- 【Gamma】“北航社团帮”发布说明——小程序v3.0
目录 Gamma版本新功能 小程序v3.0新功能 新功能列表 新功能展示 这一版修复的缺陷 Gamma版本的已知问题和限制 小程序端 网页端 运行.安装与发布 运行环境的要求 安装与发布 小程序 网页 ...
- 【操作系统之十二】分支预测、CPU亲和性(affinity)
一.分支预测 当包含流水线技术的处理器处理分支指令时就会遇到一个问题,根据判定条件的真/假的不同,有可能会产生转跳,而这会打断流水线中指令的处理,因为处理器无法确定该指令的下一条指令,直到分支执行完毕 ...
- Shell脚本之五 基本运算符
Shell 和其他编程语言一样,支持多种运算符,包括: 算数运算符 关系运算符 布尔运算符 字符串运算符 文件测试运算符 原生bash不支持简单的数学运算,但是可以通过其他命令来实现,例如 awk 和 ...
- 【layui】日期选择一闪而过问题
添加 trigger: 'click',
- git clean解决 GIT error: The following untracked working tree files would be overwritten
git clean用法:https://www.cnblogs.com/lsgxeva/p/8540476.html :
- nginx php上传大小设置
来源:http://blog.51yip.com/apachenginx/1751.html
- Python格式化输出——format用法示例
format OR % 提到Python中的格式化输出方法,一般来说有以下两种方式: print('hello %s' % 'world') # hello world print('hello {} ...
- ASP.NET Core中app.UseDeveloperExceptionPage和app.UseExceptionHandler方法有什么用
在新建一个ASP.NET Core项目后,在项目Startup类的Configure方法中默认会添加两个方法的调用,app.UseDeveloperExceptionPage和app.UseExcep ...
- Reactive MySQL Client
Reactive MySQL Client是MySQL的客户端,具有直观的API,侧重于可伸缩性和低开销. 特征 事件驱动 轻量级 内置连接池 准备好的查询缓存 游标支持 行流 RxJava 1和Rx ...