前言
最近在系统的学习 PHP ,参考的资料是《PHP编程》+ 官方文档(如果你有好的学习资料,欢迎推荐给我)。虽然这本《PHP编程》是基于 PHP5 的,但我笔记里的代码,全部在 PHP 7.2 的环境里测试过,是能够运行的。另,本笔记中只记录我模糊不清的知识。
访问数据库
在 PHP 中访问数据有两种方法:
- 使用数据库特定的拓展
- 使用不受数据库约束的 PDO ( PHP 数据对象)库
如果使用数据库特定的扩展,你的代码会和你所使用的数据库密切相关。也就是说你先把数据库从 MySQL 迁移到 PostgreSQL ,会引起代码的重大改动。而 PDO ,用一个抽象层为你隐藏了数据库特定的函数,因此在数据库系统间进行迁移,改变程序或 php.ini 文件中的一行代码这么简单。但是这种可移植性也是有代价的。使用 PDO 的代码会比使用原生数据库特定扩展的代码在执行速度上慢一点。
需要注意的是,抽象层并不能保证你的 SQL 语句是真正可移植的。如果你的应用使用了任何非泛型的 SQL ,那么在数据库迁移时你不得不对 SQL 语句进行重大改造。
PDO ( PHP 数据对象)
连接
$db = new PDO($dsn, $username, $password);$db = new PDO("mysql:host=localhost;bdname=text", "username", "password");
数据库交互
使用 query() 函数
$db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');$result = $db->query("select * from users");foreach($result as $row){print_r($row);}$result = null; // 释放结果集对象
预处理语句
先使用预处理函数 prepare() ,在运行执行函数 execute() 。
$db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');$result = $db->prepare("select * from users");$result->execute();while ($row = $result->fetch()) {print_r($row);}$result = null; // 释放结果集对象
利用占位符来进行重复插入
$db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');$statement = $db->prepare("insert into posts (title, body) values (:title, :body)");$statement->execute(['title' => 'What is PHP?','body' => 'best language']);$db = null;
也可以使用位置占位符(不命名),用 ? 标志。
$db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');$statement = $db->prepare("insert into posts (title, body) values (?, ?)");$statement->execute(['What is PHP?', 'best language']);$db = null;
事务
使用函数 beginTransaction() 开始事务, commit() 提交事务, rollback() 取消事务。
try {$db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');echo "Connected\n";} catch (Exception $e) {die("Unable to connect: " . $e->getMessage());}try {$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);$dbh->beginTransaction();$dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");$dbh->exec("insert into salarychange (id, amount, changedate)values (23, 50000, NOW())");$dbh->commit();} catch (Exception $e) {$dbh->rollBack();echo "Failed: " . $e->getMessage();}
MySQLi
MySQLi , MySQL 改进扩展( MySQL Improved )。
连接
$db = new mysqli(host, user, password, databaseName);$db = new mysqli("localhost", "root", "root", "laravelblog");
数据库交互
$db = new mysqli("localhost", "root", "root", "laravelblog");$sql = "select * from users";$result = $db->query($sql);while ($row = $result->fetch_assoc()) {print_r($row);}$result->close();$db->close();
文件操作
当我们不想使用数据库时,我们可以用文件代替它。但是功能有限。
首先我们来看一下 PHP 文件管理常用函数
| 函数名 | 使用说明 | | —- | —- |
| mkdir() | 用来在服务器上创建目录 |
| file_exits() | 用来检测指定位置的文件或目录是否存在 |
| fopen() | 用来打开存在的文件用来读或写 |
| fread() | 用来读取文件内容到一个 PHP 使用的变量 |
| flock() | 用来获得文件的独占写锁 |
| fwrite() | 用来将变量中的内容写入到文件中 |
| filesize() | 当读取文件时,这个用来检测一次需要读取的字节数 |
| fclose() | 用来当文件的实用性已经过去时,关闭文件 |
fopen() 中的参数
| 参数 | 说明 | | —- | —- |
| r | 只读方式打开,将文件指针指向文件头 |
| r+ | 读写方式打开,将文件指针指向文件头 |
| w | 写入方式打开,将文件指针指向文件头并将文件大小截为零,如果文件不存在则尝试创建之 |
| w+ | 读写方式打开,将文件指针指向文件头并将文件大小截为零,如果文件不存在则尝试创建之 |
| a | 写入方式打开,将文件指针指向文件末尾进行写入,如果文件不存在则尝试创建之 |
| a+ | 读写方式打开,通过将文件指针指向文件末尾进行写入来保存文件内容 |
| x | 创建一个新的文件并以写入方式打开,如果文件已存在则返回 FALSE 和一个错误 |
| x+ | 建一个新的文件并以读写方式打开,如果文件已存在则返回 FALSE 和一个错误 |
下面我会利用 PHP 的文件操作来创建一个动态页面。类似一个问卷调查的形式。
首先要通过唯一标识来区别用户,这里我们假定个人邮箱是唯一的(这样并不安全)。我们一旦获取用户的电子邮件地址,需要把信息存在在一个对每个访问者不同的位置。为此,我们为每个访问者在服务器上创建目录文件夹。
<?phpsession_start();if (!empty($_POST['posted']) && !empty($_POST['email'])) {$folder = "surveys/" . strtolower($_POST['email']);//向会话发送路径消息$_SESSION['folder'] = $folder;if (!file_exists($folder)) {//创建目录并添加文件mkdir($folder, 0777, true);}header("Location: 08_6.php");} else {?><!DOCTYPE html><head><title>Files & folders - On-line Survey</title></head><body bgcolor="white" text="black"><h2>Survey Form</h2><p>Please enter your e-mail address to start recording your comments</p><form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST"><input type="hidden" name="posted" value="1"><p>Email address: <input type="text" name="email" size="45" /><br /><input type="submit" value="Submit" name="submit"></p></form></body></html><?php } ?>
向通过电子邮箱创建目录,进而进行问卷调查。
<?phpsession_start();$folder = $_SESSION['folder'];$filename = $folder . "/question.txt";$file_handle = fopen($filename, "a+");//向判断文件中是否有数据if (filesize($filename) > 0) {//获取文件中已存在的任何文本$comments = fread($file_handle, filesize($filename));} else {$comments = '';}fclose($file_handle);if (!empty($_POST['posted'])) {//首次访问创建文件,然后存储 $_POST['question']中的文本$question = $_POST['question'];$file_handle = fopen($filename, "w+");if (flock($file_handle, LOCK_EX)) {if (fwrite($file_handle, $question) == false) {echo "Cannot write to file {$filename}";}flock($file_handle, LOCK_UN);}fclose($file_handle);header("Location: thank_your.php");} else {?><!DOCTYPE html><head><title>Files & folders - On-line Survey</title></head><body><table border="0"><tr><td>Please enter your response to the following survey question:</td></tr><tr bgcolor="red"><td>What is your opinion on the state of the world economy><br />Can you help us fix it ?</td></tr><tr><td><form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST"><input type="hidden" name="posted" value="1"> <br /><textarea name="question" cols="35" rows="12"><?php echo $comments ?></textarea><input type="submit" name="submit" value="Submit"></form></td></tr></table></body></html><?php } ?>
调查开始,通过表单来提交到 PHP ,进而创建相应文件。如果文件中存在数据,则打印到对应的 <textarea> 中。这里还可以继续往后面写问卷调查,要注意的是一对一,也就是一个问题一个文件。
在提交表单这里,使用了独占锁,则保证当操作它时,没有其他进程范围这个文件。这里最后我重定向到了感谢页面,表示调查的结束。
NoSQL
NoSQL , Not Only SQL 。 这里重点介绍 MongoDB 。
在 PHP 7+ 中, MongoDB 与之前的不太一样,首先要去这个网站下载 MongoDB 的扩展。对应的就是 php_mongodb.dll 。下载到的是一个压缩包,解压之后,将里面的 php_mongodb.dll 文件放入你的 PHP 目录下的 ext 文件中。最后在 php.ini 文件中写下 extension=php_mongodb.dll 重启服务器就行了。
这里演示一下插入数据(要保证 MongoDB 在运行中):
$bulk = new MongoDB\Driver\BulkWrite;$author1 = ['authorid' => 1, 'name' => 'J.R.R. Tolkien'];$bulk->insert($author1);$author2 = ['authorid' => 2, 'name' => 'Alex Haley'];$bulk->insert($author2);$author3 = ['authorid' => 3, 'name' => 'Tom Clancy'];$bulk->insert($author3);$author4 = ['authorid' => 4, 'name' => 'Isaac Asimov'];$bulk->insert($author4);$manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");$writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);$result = $manager->executeBulkWrite('test.authors', $bulk, $writeConcern);
更多的操作可以看这篇文章:php7的mongodb基本用法
感谢你看到了这里。如果文章有错误,请评论指正,谢谢!
