前言

最近在系统的学习 PHP ,参考的资料是《PHP编程》+ 官方文档(如果你有好的学习资料,欢迎推荐给我)。虽然这本《PHP编程》是基于 PHP5 的,但我笔记里的代码,全部在 PHP 7.2 的环境里测试过,是能够运行的。另,本笔记中只记录我模糊不清的知识。

访问数据库

在 PHP 中访问数据有两种方法:

  • 使用数据库特定的拓展
  • 使用不受数据库约束的 PDO ( PHP 数据对象)库

如果使用数据库特定的扩展,你的代码会和你所使用的数据库密切相关。也就是说你先把数据库从 MySQL 迁移到 PostgreSQL ,会引起代码的重大改动。而 PDO ,用一个抽象层为你隐藏了数据库特定的函数,因此在数据库系统间进行迁移,改变程序或 php.ini 文件中的一行代码这么简单。但是这种可移植性也是有代价的。使用 PDO 的代码会比使用原生数据库特定扩展的代码在执行速度上慢一点。
需要注意的是,抽象层并不能保证你的 SQL 语句是真正可移植的。如果你的应用使用了任何非泛型的 SQL ,那么在数据库迁移时你不得不对 SQL 语句进行重大改造。

PDO ( PHP 数据对象)

连接

  1. $db = new PDO($dsn, $username, $password);
  2. $db = new PDO("mysql:host=localhost;bdname=text", "username", "password");

数据库交互

使用 query() 函数

  1. $db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');
  2. $result = $db->query("select * from users");
  3. foreach($result as $row){
  4. print_r($row);
  5. }
  6. $result = null; // 释放结果集对象

预处理语句

先使用预处理函数 prepare() ,在运行执行函数 execute()

  1. $db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');
  2. $result = $db->prepare("select * from users");
  3. $result->execute();
  4. while ($row = $result->fetch()) {
  5. print_r($row);
  6. }
  7. $result = null; // 释放结果集对象

利用占位符来进行重复插入

  1. $db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');
  2. $statement = $db->prepare("insert into posts (title, body) values (:title, :body)");
  3. $statement->execute([
  4. 'title' => 'What is PHP?',
  5. 'body' => 'best language'
  6. ]);
  7. $db = null;

也可以使用位置占位符(不命名),用 ? 标志。

  1. $db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');
  2. $statement = $db->prepare("insert into posts (title, body) values (?, ?)");
  3. $statement->execute(['What is PHP?', 'best language']);
  4. $db = null;

事务

使用函数 beginTransaction() 开始事务, commit() 提交事务, rollback() 取消事务。

  1. try {
  2. $db = new PDO("mysql:host=localhost;dbname=laravelblog", 'root', 'root');
  3. echo "Connected\n";
  4. } catch (Exception $e) {
  5. die("Unable to connect: " . $e->getMessage());
  6. }
  7. try {
  8. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  9. $dbh->beginTransaction();
  10. $dbh->exec("insert into staff (id, first, last) values (23, 'Joe', 'Bloggs')");
  11. $dbh->exec("insert into salarychange (id, amount, changedate)
  12. values (23, 50000, NOW())");
  13. $dbh->commit();
  14. } catch (Exception $e) {
  15. $dbh->rollBack();
  16. echo "Failed: " . $e->getMessage();
  17. }

MySQLi

MySQLi , MySQL 改进扩展( MySQL Improved )。

连接

  1. $db = new mysqli(host, user, password, databaseName);
  2. $db = new mysqli("localhost", "root", "root", "laravelblog");

数据库交互

  1. $db = new mysqli("localhost", "root", "root", "laravelblog");
  2. $sql = "select * from users";
  3. $result = $db->query($sql);
  4. while ($row = $result->fetch_assoc()) {
  5. print_r($row);
  6. }
  7. $result->close();
  8. $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 的文件操作来创建一个动态页面。类似一个问卷调查的形式。
首先要通过唯一标识来区别用户,这里我们假定个人邮箱是唯一的(这样并不安全)。我们一旦获取用户的电子邮件地址,需要把信息存在在一个对每个访问者不同的位置。为此,我们为每个访问者在服务器上创建目录文件夹。

  1. <?php
  2. session_start();
  3. if (!empty($_POST['posted']) && !empty($_POST['email'])) {
  4. $folder = "surveys/" . strtolower($_POST['email']);
  5. //向会话发送路径消息
  6. $_SESSION['folder'] = $folder;
  7. if (!file_exists($folder)) {
  8. //创建目录并添加文件
  9. mkdir($folder, 0777, true);
  10. }
  11. header("Location: 08_6.php");
  12. } else {
  13. ?>
  14. <!DOCTYPE html>
  15. <head>
  16. <title>Files & folders - On-line Survey</title>
  17. </head>
  18. <body bgcolor="white" text="black">
  19. <h2>Survey Form</h2>
  20. <p>Please enter your e-mail address to start recording your comments</p>
  21. <form action="<?php echo $_SERVER['PHP_SELF'] ?>" method="POST">
  22. <input type="hidden" name="posted" value="1">
  23. <p>Email address: <input type="text" name="email" size="45" /><br />
  24. <input type="submit" value="Submit" name="submit"></p>
  25. </form>
  26. </body>
  27. </html>
  28. <?php } ?>

向通过电子邮箱创建目录,进而进行问卷调查。

  1. <?php
  2. session_start();
  3. $folder = $_SESSION['folder'];
  4. $filename = $folder . "/question.txt";
  5. $file_handle = fopen($filename, "a+");
  6. //向判断文件中是否有数据
  7. if (filesize($filename) > 0) {
  8. //获取文件中已存在的任何文本
  9. $comments = fread($file_handle, filesize($filename));
  10. } else {
  11. $comments = '';
  12. }
  13. fclose($file_handle);
  14. if (!empty($_POST['posted'])) {
  15. //首次访问创建文件,然后存储 $_POST['question']中的文本
  16. $question = $_POST['question'];
  17. $file_handle = fopen($filename, "w+");
  18. if (flock($file_handle, LOCK_EX)) {
  19. if (fwrite($file_handle, $question) == false) {
  20. echo "Cannot write to file {$filename}";
  21. }
  22. flock($file_handle, LOCK_UN);
  23. }
  24. fclose($file_handle);
  25. header("Location: thank_your.php");
  26. } else {
  27. ?>
  28. <!DOCTYPE html>
  29. <head>
  30. <title>Files & folders - On-line Survey</title>
  31. </head>
  32. <body>
  33. <table border="0">
  34. <tr>
  35. <td>
  36. Please enter your response to the following survey question:
  37. </td>
  38. </tr>
  39. <tr bgcolor="red">
  40. <td>
  41. What is your opinion on the state of the world economy><br />
  42. Can you help us fix it ?
  43. </td>
  44. </tr>
  45. <tr>
  46. <td>
  47. <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
  48. <input type="hidden" name="posted" value="1"> <br />
  49. <textarea name="question" cols="35" rows="12"><?php echo $comments ?></textarea>
  50. <input type="submit" name="submit" value="Submit">
  51. </form>
  52. </td>
  53. </tr>
  54. </table>
  55. </body>
  56. </html>
  57. <?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 在运行中):

  1. $bulk = new MongoDB\Driver\BulkWrite;
  2. $author1 = ['authorid' => 1, 'name' => 'J.R.R. Tolkien'];
  3. $bulk->insert($author1);
  4. $author2 = ['authorid' => 2, 'name' => 'Alex Haley'];
  5. $bulk->insert($author2);
  6. $author3 = ['authorid' => 3, 'name' => 'Tom Clancy'];
  7. $bulk->insert($author3);
  8. $author4 = ['authorid' => 4, 'name' => 'Isaac Asimov'];
  9. $bulk->insert($author4);
  10. $manager = new MongoDB\Driver\Manager("mongodb://localhost:27017");
  11. $writeConcern = new MongoDB\Driver\WriteConcern(MongoDB\Driver\WriteConcern::MAJORITY, 1000);
  12. $result = $manager->executeBulkWrite('test.authors', $bulk, $writeConcern);

更多的操作可以看这篇文章:php7的mongodb基本用法

感谢你看到了这里。如果文章有错误,请评论指正,谢谢!