数据保存有多种方式,比如单机文件(JSON、txt)、单机数据库(SQLite、Access)、网络数据库(MySQL/MariaDB、Oracle、SQL Server)等等,根据项目需要进行选型。做Web一般采用开源并且免费的MySQL/MariaDB,本书也以MySQL为例。
CREATE DATABASE `reader` DEFAULT CHARACTER SET utf8;
USE `reader`;
CREATE TABLE `articles` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`author` varchar(20) DEFAULT NULL,
`title` varchar(50) DEFAULT NULL,
`content` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
<?php
$input = $_POST;
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=reader;charset=utf8';
$user = 'root';
$password = '1';
$db = new PDO($dsn, $user, $password); //连接数据库
$sql = 'INSERT INTO `articles` (`author`, `title`, `content`) VALUES (' . '\'' . $input['author'] . '\',\'' . $input['title'] . '\',\'' . $input['content'] . '\');';
$stmt = $db->query($sql); //执行SQL
$id = $db->lastInsertId(); //获得自增id
if (!empty($id)) {
$notice = '保存成功';
} else {
$notice = '出错了';
}
$d = array();
$d['notice'] = array(
'msg' => $notice,
);
require_once __DIR__ . '/notice.html';
<?php
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=reader;charset=utf8';
$user = 'root';
$password = '1';
$db = new PDO($dsn, $user, $password);
$sql = 'SELECT `id`, `author`, `title`, `content` FROM `articles` LIMIT 10';
$stmt = $db->query($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$articles = $stmt->fetchAll();
$d = array();
$d['articles'] = $articles;
require_once __DIR__ . '/index.html';
<?php
$input = $_GET;
$d = array();
if (!isset($input['id']) || empty($input['id'])) {
$d['notice'] = array(
'msg' => '出错了:缺少参数',
);
require __DIR__ . '/notice.html';
exit;
}
$dsn = 'mysql:host=127.0.0.1;port=3306;dbname=reader;charset=utf8';
$user = 'root';
$password = '1';
$db = new PDO($dsn, $user, $password);
$sql = 'SELECT `author`, `title`, `content` FROM `articles` WHERE id=' . $input['id'] . ' LIMIT 1';
$stmt = $db->query($sql);
$stmt->setFetchMode(PDO::FETCH_ASSOC);
$r = $stmt->fetchAll();
if (empty($r)) {
$d['notice'] = array(
'msg' => '出错了:查无此文',
);
require __DIR__ . '/notice.html';
exit;
}
$d = array();
$d['article'] = $r[0];
require_once __DIR__ . '/get_article.html';