之前系列中內(nèi)容有介紹過 PDO 進(jìn)行數(shù)據(jù)庫查詢并顯示數(shù)據(jù),這回將描述如何通過它向表中插入數(shù)據(jù)。
小實(shí)踐
接下的內(nèi)容都是建立在之前系列內(nèi)容的代碼基礎(chǔ)上。
首先,在之前的數(shù)據(jù)庫 mytodo
數(shù)據(jù)庫下建立一張 users
表 ,結(jié)構(gòu)如下:
CREATE TABLE `users` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL DEFAULT '',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
通過數(shù)據(jù)庫客戶端(比如
Sequel Pro
)來創(chuàng)建表也會(huì)很方便。
接下來,我們需要調(diào)整 QueryBuilder.php
,會(huì)增加一些代碼實(shí)現(xiàn)插入數(shù)據(jù)庫相關(guān)的操作。
<?php
class QueryBuilder
{
protected $pdo;
public function __construct($pdo)
{
$this->pdo = $pdo;
}
public function selectAll($table)
{
$statement = $this->pdo->prepare("select * from {$table}");
$statement->execute();
return $statement->fetchAll(PDO::FETCH_CLASS);
}
public function insert($table, $parameters)
{
$sql = sprintf(
'insert into %s(%s) values(%s)',
$table,
implode(', ', array_keys($parameters)),
':' . implode(', :', array_keys($parameters))
);
try {
$statement = $this->pdo->prepare($sql);
$statement->execute($parameters);
} catch (Exception $e) {
die('Whoops, something went wrong.'.$e->getMessage());
}
}
}
這里新增了 insert
方法,該方法會(huì)拼接傳入的表名以及列參數(shù)信息成 SQL 語句,通過 PDO 執(zhí)行操作。
這里使用了 try...catch
代碼塊用于捕獲數(shù)據(jù)庫操作中存在的異常。
我們的提交表單的請(qǐng)求會(huì)執(zhí)行到 controllers/add-name.php
中:
<?php
$app['database']->insert('users', [
'name' => $_POST['name']
]);
header('Location: /');
獲取 POST 請(qǐng)求參數(shù)信息,向 users
表插入用戶信息。
通過上面的操作,我們已經(jīng)可以完成提交表單插入數(shù)據(jù)到數(shù)據(jù)表,接下來是讀取這些數(shù)據(jù)顯示在頁面上。
首先,在 controllers/index.php
讀取數(shù)據(jù):
<?php
$users = $app['database']->selectAll('users');
require "views/index.view.php";
其次,在頁面 views/index.view.php
上添加輸出代碼:
<?php require('partials/head.php'); ?>
<?php foreach ($users as $user) : ?>
<li><?= $user->name; ?></li>
<?php endforeach; ?>
<h1>Submit Your Name</h1>
<form action="/names" method="POST">
<input type="text" name="name">
<button type="Submit">Submit</button>
</form>
<?php require('partials/footer.php'); ?>
運(yùn)行程序感受一下。