连接数据库
extension_dir = "php-install-path/ext"
extension=pdo_pgsql
host=192.168.56.104
port=5432
database=hrdb
user=tony
password=tony
/**
* 数据库连接
*/
class Connection {
/**
* Connection
* @var type
*/
private static $conn;
/**
* 连接数据库并返回一个 PDO 对象实例
* @return PDO
* @throws Exception
*/
public function connect() {
// 读取数据库配置参数文件
$params = parse_ini_file('db.ini');
if ($params === false) {
throw new Exception("读取数据库配置参数文件错误!");
}
// connect to the postgresql database
$conStr = sprintf("pgsql:host=%s;port=%d;dbname=%s;user=%s;password=%s",
$params['host'],
$params['port'],
$params['database'],
$params['user'],
$params['password']);
$pdo = new PDO($conStr);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
/**
* 返回连接对象实例
* @return type
*/
public static function get() {
if (null === static::$conn) {
static::$conn = new static();
}
return static::$conn;
}
}
require 'connection.php';
try {
Connection::get()->connect();
echo '成功连接 PostgreSQL 数据库服务器!';
} catch (PDOException $e) {
echo $e->getMessage();
}
成功连接 PostgreSQL 数据库服务器!
创建和删除表
require 'connection.php';
try {
$pdo = Connection::get()->connect();
echo '成功连接 PostgreSQL 数据库服务器!
';
$sql = 'create table if not exists users (
id serial primary key,
name character varying(10) not null unique,
created_at timestamp not null
);';
$pdo->exec($sql);
echo '成功创建表 users!';
} catch (PDOException $e) {
echo $e->getMessage();
}
成功连接 PostgreSQL 数据库服务器!
成功创建表 users!
插入数据
创建一个新的 PDO 实例,通过 connect() 方法连接到数据库;
构造一个 INSERT 语句,可以通过占位符(例如 :param1)传递参数;
调用 PDO 对象的 prepare() 方法返回一个预编译语句对象 PDOStatement;
调用 PDOStatement 对象的 bindValue() 方法为参数传递数值;
最后,调用 PDOStatement 对象的 execute() 方法执行 INSERT 语句。
require 'connection.php';
try {
$pdo = Connection::get()->connect();
echo '成功连接 PostgreSQL 数据库服务器!
';
// 预编译插入语句
$sql = 'INSERT INTO users(name, created_at) VALUES(:name,:createdAt)';
$stmt = $pdo->prepare($sql);
// 绑定参数值
$name = 'tony';
$createdAt = '2020-06-03 11:30:16';
$stmt->bindValue(':name', $name);
$stmt->bindValue(':createdAt', $createdAt);
// 执行插入操作
$stmt->execute();
// 返回id
$id = $pdo->lastInsertId('users_id_seq');
echo '插入数据成功,用户id:' . $id . '
';
// 绑定参数值
$name = 'david';
$createdAt = '2020-06-01 20:11:11';
$stmt->bindValue(':name', $name);
$stmt->bindValue(':createdAt', $createdAt);
// 执行插入操作
$stmt->execute();
// 返回id
$id = $pdo->lastInsertId('users_id_seq');
echo '插入数据成功,用户id:' . $id . '
';
} catch (PDOException $e) {
echo $e->getMessage();
}
成功连接 PostgreSQL 数据库服务器!
插入数据成功,用户id:1
插入数据成功,用户id:2
查询数据
创建一个新的 PDO 实例,通过 connect() 方法连接到数据库;
调用 PDO 对象的 query() 方法,传入一个查询语句文本,返回一个 PDOStatement 对象;
调用 PDOstatement 对象的 fetch() 方法从查询结果中返回下一行数据。该方法的 fetch_style 参数决定了返回结果的方式。
require 'connection.php';
try {
$pdo = Connection::get()->connect();
// 执行查询语句
$stmt = $pdo->query('SELECT id, name, created_at FROM users');
$users = [];
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$users[] = [
'id' => $row['id'],
'name' => $row['name'],
'createdAt' => $row['created_at']
];
}
} catch (PDOException $e) {
echo $e->getMessage();
}
?>
DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
style>
<title>查询用户数据title>
head>
<body>
<h2>用户列表h2>
<table>
<thead>
<tr>
<th>IDth>
<th>Nameth>
<th>CreatedAtth>
tr>
thead>
<tbody>
php foreach ($users as $user) : ?>
<tr>
<td>php echo htmlspecialchars($user['id']) ?>td>
<td>php echo htmlspecialchars($user['name']); ?>td>
<td>php echo htmlspecialchars($user['createdAt']); ?>td>
tr>
php endforeach; ?>
tbody>
table>
body>
html>
修改数据
require 'connection.php';
try {
$pdo = Connection::get()->connect();
// 预编译更新语句
$sql = 'UPDATE users '
. 'SET name = :name '
. 'WHERE id = :id';
$stmt = $pdo->prepare($sql);
// 绑定参数值
$name = 'tom';
$id = 1;
$stmt->bindValue(':name', $name);
$stmt->bindValue(':id', $id);
// 执行更新操作
$stmt->execute();
// 返回更新的行数
$rowCount = $stmt->rowCount();
echo '更新数据成功,更新记录数:' . $rowCount . '
';
} catch (PDOException $e) {
echo $e->getMessage();
}
更新数据成功,更新记录数:1
删除数据
require 'connection.php';
try {
$pdo = Connection::get()->connect();
// 预编译删除语句
$sql = 'DELETE FROM users '
. 'WHERE id = :id';
$stmt = $pdo->prepare($sql);
// 绑定参数值
$id = 1;
$stmt->bindValue(':id', $id);
// 执行删除操作
$stmt->execute();
// 返回删除的行数
$rowCount = $stmt->rowCount();;
echo '删除数据成功,删除记录数:' . $rowCount . '
';
} catch (PDOException $e) {
echo $e->getMessage();
}
删除数据成功,删除记录数:1
管理事务
require 'connection.php';
try {
$pdo = Connection::get()->connect();
echo '成功连接 PostgreSQL 数据库服务器!
';
$pdo->beginTransaction();
// 预编译插入语句
$sql = 'INSERT INTO users(name, created_at) VALUES(:name,:createdAt)';
$stmt = $pdo->prepare($sql);
// 绑定参数值
$name = 'bob';
$createdAt = '2020-06-04 22:00:00';
$stmt->bindValue(':name', $name);
$stmt->bindValue(':createdAt', $createdAt);
// 执行插入操作
$stmt->execute();
// 返回id
$id = $pdo->lastInsertId('users_id_seq');
echo '插入数据成功,用户id:' . $id . '
';
// 预编译更新语句
$sql = 'UPDATE users '
. 'SET name = :name '
. 'WHERE id = :id';
$stmt = $pdo->prepare($sql);
// 绑定参数值
$name = 'david';
$stmt->bindValue(':name', $name);
$stmt->bindValue(':id', $id);
// 执行更新操作
$stmt->execute();
// 返回更新的行数
$rowCount = $stmt->rowCount();;
echo '更新数据成功,更新记录数:' . $rowCount . '
';
$pdo->commit();
} catch (PDOException $e) {
$pdo->rollBack();
echo '执行操作失败,回滚事务!' . '
';
echo $e->getMessage();
}
成功连接 PostgreSQL 数据库服务器!
插入数据成功,用户id:4
执行操作失败,回滚事务!
SQLSTATE[23505]: Unique violation: 7 ERROR: duplicate key value violates unique constraint "users_name_key" DETAIL: Key (name)=(david) already exists.
调用存储过程
CREATE OR REPLACE PROCEDURE add_user(pv_name varchar, pd_created_at timestamp)
AS $$
BEGIN
insert into users(name, created_at)
values (pv_name, pd_created_at);
END; $$
LANGUAGE plpgsql;
require 'connection.php';
try {
$pdo = Connection::get()->connect();
// 预编译语句
$sql = 'call add_user(:name,:createdAt)';
$stmt = $pdo->prepare($sql);
// 绑定参数值
$name = 'anne';
$createdAt = '2020-06-04 08:08:08';
$stmt->bindValue(':name', $name);
$stmt->bindValue(':createdAt', $createdAt);
// 执行操作
$stmt->execute();
// 返回id
$id = $pdo->lastInsertId('users_id_seq');
echo '插入数据成功,用户id:' . $id . '
';
} catch (PDOException $e) {
echo $e->getMessage();
}
插入数据成功,用户id:6