对于我们之前的应用程序,它只是用户配置文件,我们只创建了一个简单的**创建读取更新删除(CRUD)**数据库抽象层—基本内容。在本章中,我们将创建一个更好的数据库抽象层,它将允许我们做的不仅仅是基本的数据库功能。
除了简单的 CRUD 特性外,我们还将在混合中添加结果操纵。我们将在数据库抽象类中构建以下功能:
- 将整数转换为其他更精确的数字类型
- 数组到对象的转换
firstOf()
方法:允许我们选择数据库查询的第一个结果lastOf()
方法:允许我们选择数据库查询的最后一个结果iterate()
方法:允许我们对结果进行迭代,并以发送给此函数的格式返回结果searchString()
方法:在结果列表中查找字符串
我们可以在需要时添加更多函数。在本章末尾,我们将应用数据库抽象层构建一个简单的购物车系统。
购物车很简单:已经登录的用户应该能够点击一些待售商品,点击添加到购物车,并获取用户的详细信息。在用户验证了他们的商品后,他们单击按钮进行购买,我们将把他们的购物车商品转移到采购订单中,他们将在订单中填写送货地址,然后将其保存到数据库中。
在 PHP 中,创建类时,有一种方法可以在每次初始化该类时调用某个方法。这称为类的构造函数。大多数类都有构造函数,因此我们将有自己的构造函数。构造函数用两个带construct()
关键字的下划线命名,如下所示:function __construct()
。带有两个下划线的函数也称为魔术方法。
在我们的数据库抽象类中,我们需要创建一个构造函数,以便能够返回由mysqli
生成的link
对象:
Class DB {
public $db;
//constructor
function __construct($server, $dbname,$user,$pass) {
//returns mysqli $link $link = mysqli_connect('');
return $this->db = mysqli_connect($server, $dbname, $user, $pass);
}
}
query
方法将只执行对传递给它的任何内容的查询。我们将在query
方法中调用 MySQLi 的db->query
方法。
下面是它的外观:
public function query($sql) {
$results = $this->db->query($sql);
return $results;
}
对于我们的数据库层,让我们创建create
方法。这样,我们将使用 SQL 语法将项插入到数据库中。在 MySQL 中,语法如下:
INSERT INTO [TABLE] VALUES ([val1], [val2], [val3]);
我们需要一种方法将数组值转换为字符串,每个值用逗号分隔:
function create ($table, $arrayValues) {
$query = "INSERT INTO `" . $table . " ($arrayVal); //TODO: setup arrayVal
$results = $this->db->query($link, $query);
}
对于我们的db
层,让我们创建read
方法。这样,我们就可以使用 SQL 语法查询数据库了。
MySQL 中的语法如下:
SELECT * FROM [table] WHERE [key] = [value]
我们需要创建一个能够接受括号中前面参数的函数:
public function read($table, $key, $value){
$query = SELECT * FROM $table WHERE `". $key . "` = " . $value;
return $this->db->query($query);
}
我们的read
方法接受key
和value
对。然而,在某些情况下,我们可能只需要选择表中的所有内容。在这种情况下,我们应该创建一个简单的方法来选择一个表中的所有行,该方法只接受选择的table
作为参数。
在 MySQL 中,您只需使用以下命令选择所有行:
SELECT * FROM [table];
我们需要创建一个能够接受括号中前面参数的函数:
public function select_all($table){
$query = "SELECT * FROM " . $table;
return $this ->query($query);
}
对于我们的db
层,让我们创建delete
方法。这样,我们将使用 SQL 语法删除数据库中的一些项。
MySQL 语法很简单:
DELETE FROM [table] WHERE [key] = [val];
我们还需要创建一个能够接受括号中前面参数的函数:
public function delete($table, $key, $value){
$query = DELETE FROM $table WHERE `". $key . "` = " . $value;
return $this->query($query);
}
对于我们的数据库层,让我们创建一个update
方法。有了它,我们将能够使用 SQL 语法更新数据库中的项。
MySQL 语法如下所示:
UPDATE [table] SET [key1] = [val1], [key2] => [val2] WHERE [key] = [value]
注意,WHERE
子句的长度可以超过一个键值对,这意味着您可以将AND
和OR
添加到语句中。这意味着,除了使第一个键是动态的,WHERE
子句需要能够接受AND
/OR
到其参数。
例如,您可以为$where
参数编写以下内容,以选择firstname
为John
且lastname
为Doe
的人员:
firstname='John' AND lastname='Doe'
这就是为什么我们将条件设置为函数中的字符串参数。我们数据库类中的update
方法最终将如下所示:
public function update($table, $updateSetArray, $where){
Foreach($updateSetArray as $key => $value) {
$update_fields .= $key . "=" . $value . ",";
}
//remove last comma from the foreach loop above
$update_fields = substr($update_fields,0, str_len($update_fields)-1);
$query = "UPDATE " . $table. " SET " . $updateFields . " WHERE " $where; //the where
return $this->query($query);
}
在我们的数据库中,我们将创建一个first_of
方法,该方法将过滤掉其余的结果,只得到第一个结果。我们将使用 PHP 的reset
函数,它只获取数组中的第一个元素:
//inside DB class
public function first_of($results) {
return reset($results);
}
last_of
方法相似;我们可以使用 PHP 的end
函数:
//inside DB class
public function last_of($results) {
Return end($results);
}
iterate_over
方法将是一个函数,它简单地将格式(HTML 代码之前和之后)添加到字符串中,例如,对于我们从数据库获得的每个结果:
public function iterate_over($prefix, $postfix, $items) {
$ret_val = '';
foreach($items as $item) {
$ret_val .= $prefix. $item . $postfix;
}
return $ret_val;
}
给定一组结果,我们将在某个字段中查找要搜索的内容。方法是生成如下所示的 SQL 代码:
SELECT * FROM {table} WHERE {field} LIKE '%{searchString}%';
函数将接受表,以及检查表中搜索字符串needle
的字段:
public function search_string($table, $column, $needle) {
$results = $this->query("SELECT * FROM `".$table."` WHERE " . $column . " LIKE '%" . $needle. "%'");
return $results;
}
有时,我们希望数据库的结果采用特定的格式。例如,当我们将结果作为 JSON 对象而不是数组处理时。这在构建移动应用程序使用的简单 API 时非常有用。
这可能是可能的,例如,在另一个系统中,它需要某种格式,例如 JSON 格式,我们可以使用 JSON 格式将对象转换为 JSON 并发送给它。
在 PHP 中,有json_encode
方法,它将任何数组或对象转换为 JSON 符号。我们的类的方法将只返回传递给它的值作为json
:
function convertToJSON($object) {
return json_encode($object);
}
现在我们将构建一个简化的购物车模块,它将利用我们新构建的数据库抽象类。
让我们规划一下购物车的功能:
- Shopping List page:
- 购物者应该看到几件商品的名称和价格
- 购物者应该能够点击每个项目旁边的复选框,将其添加到购物车
- Checkout page:
- 物品清单及其价格
- 全部的
- Confirmation page:
- 输入详细信息,例如账单地址、账单信用卡号码,当然还有姓名
- 购物者还应该能够指定将商品发送到哪个地址
在这个页面中,我们将创建基本的 HTML 块来显示购物者可能希望购买的物品列表。
我们将使用与前面相同的模板系统,但我们将分离页眉和页脚,并使用include()
将它们包含在我们的文件中,而不是将整个代码放在一个页面中。我们还将使用相同的引导框架使前端看起来更漂亮。
我们将创建 item render 函数,该函数将在div
中呈现我们所有的购物项目。函数将简单地返回项目的 HTML 标记,其中包含项目的价格、名称和图片图像:
//accepts the database results as an array and calls db functions render_shopping_items($items)
{
$db->iterate_over("<td>", "</td>", $item_name);
foreach($items as $item) {
$item->name. ' ' .$item->price . ' ' . $item->pic;
}
$resultTable .= "</table>";
}
在前面的代码中,我们使用了新创建的iterate_over
函数,它格式化数据库的每个值。最终的结果是,我们有一个表的项目,我们想买。
让我们创建一个简单的布局结构,只需在我们构建的每个页面中获取页眉和页脚,从现在起,只需包含它们:
在header.php
中:
<html>
<!doctype html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
</head>
<body>
在footer.php
中:
<div class="footer">Copyright 2016</div></body>
</html>
在index.php
中:
<?php
require('header.php');
//render item_list code goes here
require('itemslist.php'); //to be coded
require('footer.php');
?>
现在让我们创建itemslist.php
页面,该页面将包含在index.php
中:
<?php
include('DB.php');
$db = new DB();
$table = 'shopping_items';
$results = $db->select_all($table);
//calling the render function created earlier:
foreach(as $item) {
echo render_shopping_items($results);
}
?>
//shopping items list goes here.
我们的功能已经就绪,但我们的数据库还不存在。我们还需要填充数据库。
让我们通过在 MySQL 数据库中创建shopping_items
表来创建一些购物项目:
CREATE TABLE shopping_items (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
price DECIMAL(6,2) NOT NULL,
image VARCHAR(255) NOT NULL,
PRIMARY KEY (id)
);
让我们运行 MySQL 并将以下项目插入数据库:
INSERT INTO `shopping_items` VALUES (NULL,'Tablet', '199.99', 'tablet.png');
INSERT INTO `shopping_items` VALUES (NULL, 'Cellphone', '199.99', 'cellphone.png');
INSERT INTO `shopping_items` (NULL,'Laptop', '599.99', 'Laptop.png');
INSERT INTO `shopping_items` (NULL,'Cable', '14.99', 'Cable.png');
INSERT INTO `shopping_items` (NULL, 'Watch', '100.99', 'Watch.png');
让我们将其保存在文件insert_shopping_items.sql
中。然后,在与insert_shopping_items.sql
文件相同的目录中:
-
登录 MySQL 客户端,按照以下步骤操作:
mysql -u root -p
-
然后键入
use <name of database>
:mysql> use <database>;
-
使用
source
命令mysql> source insert_shopping_items.sql
导入脚本
当我们运行SELECT * FROM shopping_items
时,我们应该看到以下内容:
现在,让我们创建 HTML 复选框,以便用户能够选择购物项目。我们将创建表单以插入数据,如下所示:
//items.php
<html>
<body>
<form action="post_profile.php" method="POST">
<table>
<input type="checkbox" value="<item_id>"> <td><item_image></td>
<td><item_name></td><td>
</table>
</form>
</body>
</html>
为此,我们需要修改render_items
方法以添加复选框:
public function render_items($itemsArray) {
foreach($itemsArray as $item) {
return '<tr>
<td><input type="checkbox" name="item[]" value="' . $item->id. '">' . . '</td><td>' . $item->image .'</td>
<td>'. $item->name . '</td>
'<td>'.$item->price . '</td>
'</tr>';
}
}
在下一页中,当用户单击提交时,我们必须获取数组中的所有 ID。
因为我们将复选框命名为item[]
,所以我们应该能够通过$_POST['item']
作为数组获取值。基本上,所有被检查的项目都将作为一个数组进入 PHP 的$_POST
变量,这将允许我们获得将数据保存到数据库中的所有值。让我们循环查看结果的 ID,获取数据库中每个项目的价格,并将每个项目保存在名为itemsArray
的数组中,键作为项目名称,其价格作为项目值:
$db = new DB();
$itemsArray= []; //to contain our items - since PHP 5.4, an array can be defined with [];
foreach($_POST['item'] as $itemId) {
$item = $db->read('shopping_items', 'id', $itemId);
//this produces the equivalent SQL code: SELECT * FROM shopping_items WHERE id = '$itemId';
$itemsArray[$item->name] = $item-price;
}
我们将首先与用户确认购买的物品。我们现在只将项目和总金额保存到 cookie 中。我们将在签出页面上访问 cookie 的值,该页面将接受用户的详细信息,并在提交签出页面时将其保存到我们的数据库中。
PHP 会话与 Cookie:对于不太敏感的数据,例如用户购买的项目列表,我们可以使用 Cookie,它实际将数据(以纯文本形式!)存储在浏览器中。如果您正在构建此应用程序并在生产中使用它,建议使用会话。要了解有关会话的更多信息,请转至http://php.net/manual/en/features.sessions.php 。
在 PHP 中,要启动 cookie,只需调用setcookie
函数。为了将购买的物品保存到 cookie 中,我们必须序列化数组,原因是 cookie 仅将值存储为字符串。
在这里,我们将项目保存到 cookie 中:
setcookie('purchased_items', serialize($itemsArray), time() + 900);
前面的 cookie 将项目作为数组存储在purchased_items
cookie 中。它将在 15 分钟(900 秒)后过期。但是,请注意对time()
函数的调用,该函数返回当前时间的 Unix 时间戳。当达到最后一个参数中设置的时间时,PHP 中的 Cookie 将过期。
调试基于 cookie 的应用程序有时令人沮丧。确保time()
生成的时间戳确实显示了当前时间。
例如,您可能最近重新格式化了计算机,但由于某些原因无法正确设置时间。要测试time()
,只需使用time()
调用运行一个 PHP 脚本并检查http://www.unixtimestamp.com/ 如果它们几乎相同。
最后,我们将创建一个表单,用户可以在其中输入签出后的详细信息。
我们首先需要为客户构建数据库表。我们把这张桌子叫做purchases
。我们需要存储客户的姓名、地址、电子邮件、信用卡、购买的物品以及总数。我们还应该存储购买交易的时间,并使用唯一的主键对每一行进行索引。
下面是要导入 MySQL 数据库的表模式:
CREATE TABLE purchases (
id INT(11) NOT NULL AUTO_INCREMENT,
customer_name VARCHAR(255) NOT NULL,
address DECIMAL(6,2) NOT NULL,
email DECIMAL(6,2) NOT NULL,
credit_card VARCHAR(255) NOT NULL,
items TEXT NOT NULL,
total DECIMAL(6,2) NOT NULL,
created DATETIME NOT NULL,
PRIMARY KEY (id)
);
导入的一种方法是创建一个文件purchases.sql
,然后登录 MySQL 命令行工具。
然后,您可以选择要使用的数据库:
USE <databasename>
最后,假设您与purchases.sql
在同一目录下,您可以运行:
SOURCE purchases.sql
最后,让我们创建一个简单的表单,其中包含详细信息的输入字段,如地址、信用卡和买家姓名:
<form action="save_checkout.php" method="post">
<table>
<tr>
<td>Name</td><td><input type="text" name="fullname"></td>
</tr>
<tr>
<td>Address</td><td><input type="text" name="address"></td>
</tr>
<tr>
<td>Email</td><td><input type="text" name="email"></td>
</tr>
<tr>
<td>Credit Card</td><td><input type="text" name="credit_card"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="submit" value="Purchase"></td>
</tr>
</table>
</form>
下面是它的外观:
最后,我们将一如既往地使用DB
类将所有内容保存到数据库中的另一个表中。为了计算总金额,我们将查询数据库中的价格,并使用 PHP 的array_sum
得到总金额:
$db = new DB($server,$dbname,$name,$password);
//let's get the other details of the customer
$customer_name = $_POST['fullname'];
$address = $_POST['address'];
$email = $_POST['email'];
$credit_card = $_POST['credit_card];
$time_now = date('Y-m-d H:i:s');
foreach($purchased_items as $item) {
$prices[] = $item->price;
}
//get total using array_sum
$total = array_sum($prices);
$db->insert('purchases', [
'address' => $address,
'email' => $email,
'credit_card' => $credit_card,
'items' => //<all the items and prices>//,
'total' => $total,
'purchase_date' => $timenow
]);
?>
为了保持简单,正如您在突出显示的代码中所看到的,我们需要将购买的所有项目收集到一个长字符串中,以便保存在数据库中。以下是您如何连接每个项目及其价格:
foreach($purchased_items as $item) {
$items_text .= $item->name ":" . $item->price . ","
}
然后我们可以将该数据保存到变量$items_text
中。我们将更新前面突出显示的代码,并将文本<all the items and prices>
改为$items_text
:
...
'items' => $items_text
...
在我们的代码中,前面的foreach
循环应该放在$db->insert
方法调用之前。
最后,我们将数据保存到purchased_items
表中。是时候向我们的客户表示感谢并发送电子邮件了。在我们的 HTML 代码thankyou.php
中,我们只需写一封感谢信,让用户知道关于他们购买的电子邮件正在发送中。
以下是一个屏幕截图:
我们将文件命名为thankyou.php
,其 HTML 代码非常简单:
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<title>Thank you for shopping at example.info</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h1>Thank you for shopping at example.info</h1>
<p>Yey! We're really happy for choosing us to shop online. We've sent you an email of your purchases. </p>
<p>Let us know right away if you need anything</p>
</div>
</div>
</div>
</body>
</html>
使用 PHP 发送电子邮件是通过mail()
函数完成的:
mail("<to address>", "Your purchase at example.com","Thank you for purchasing...", "From: <from address>");
第三个参数是我们的电子邮件消息。在代码中,我们仍然需要添加购买的详细信息。我们将循环查看我们之前制作的 cookie 和价格,然后只输出总量,并发送消息:
$mail_message = 'Thank you for purchasing the following items';
$prices = [];
$purchased_items = unserialize($_COOKIE['purchased_items']);
foreach($purchased_items as $itemName => $itemPrice) {
$mail_message .= $itemName . ": " .$itemPrice . "\r\n \r\n";
//since this is a plain text email, we will use \r\n - which are escape strings for us to add a new line after each price.
$prices[] = $itemPrice;
}
$mail_message .= "The billing total of your purchases is " . array_sum($prices);
mail($_POST['email'], "Thank you for shopping at example.info here is your bill", $mail_message, "From: billing@example.info");
我们可以在thankyou.php
文件的最后添加前面的代码位。
您可以从 sourceforge 下载 TCPDF 库,https://sourceforge.net/projects/tcpdf/
TCPDF 是一个用于编写 PDF 文档的 PHP 类。
带有 TCPDF 的 PHP 示例的示例代码如下所示:
//Taken from http://www.tcpdf.org/examples/example_001.phps
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 001');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set default font subsetting mode
$pdf->setFontSubsetting(true);
// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->SetFont('dejavusans', '', 14, '', true);
// Add a page
// This method has several options, check the source code documentation for more information.
$pdf->AddPage();
// set text shadow effect
$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
// Set some content to print
$html = <<<EOD
<h1>Welcome to <a href="http://www.tcpdf.org" style="text-decoration:none;background-color:#CC0000;color:black;"> <span style="color:black;">TC</span><span style="color:white;">PDF</span> </a>!</h1>
<i>This is the first example of TCPDF library.</i>
<p>This text is printed using the <i>writeHTMLCell()</i> method but you can also use: <i>Multicell(), writeHTML(), Write(), Cell() and Text()</i>.</p>
<p>Please check the source code documentation and other examples for further information.</p>
<p style="color:#CC0000;">TO IMPROVE AND EXPAND TCPDF I NEED YOUR SUPPORT, PLEASE <a href="http://sourceforge.net/donate/index.php?group_id=128076">MAKE A DONATION!</a></p>
EOD;
// Print text using writeHTMLCell()
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
// ---------------------------------------------------------
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
$pdf->Output('example_001.pdf', 'I');
在这个例子中,我们现在可以使用前面的代码并对其进行修改,以便创建我们自己的发票。我们所需要的只是相同的 HTML 样式和由我们的 total 生成的值。让我们使用相同的代码并将值更新为所需的值。
在这种情况下,我们将作者设置为站点的名称example.info
。并将我们的主题设置为Invoice
。
首先,我们需要获得主要的 TCPDF 库。如果您将其安装在不同的文件夹中,我们可能需要提供指向tcpdf_include.php
文件的相对路径:
require_once('tcpdf_include.php');
这将使用类中的默认方向和默认页面格式实例化一个新的 TCPDF 对象:
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Example.Info');
$pdf->SetTitle('Invoice Purchases');
$pdf->SetSubject('Invoice');
$pdf->SetKeywords('Purchases, Invoice, Shopping');
s
$html = <<<EOD
<h1>Example.info Invoice </h1>
<i>Invoice #0001.</i>
EOD;
现在,让我们使用 HTML 创建客户购买的 HTML 表:
$html .= <<<EOD
<table>
<tr>
<td>Item Purchases</td>
<td>Price</td>
</tr>
EOD;
这种写出多行字符串的方式称为 herdoc 语法。
让我们通过实例化DB
类来创建到数据库的连接:
$db = new DBClass('localhost','root','password', 'databasename');
We shall now query our database with our database class:
$table = 'purchases';
$column = 'id';
$findVal = $_GET['purchase_id'];
$result = $db->read ($table, $column, $findVal);
foreach($item = $result->fetch_assoc()) {
$html .= "<tr>
<td>". $item['customer_name']. "</td>
<td>" . $item['items'] . "
</tr>";
$total = $items['total']; //let's save the total in a variable for printing in a new row
}
$html .= '<tr><td colspan="2" align="right">TOTAL: ' ".$total. " ' </td></tr>';
$html .= <<<EOD
</table>
EOD;
$pdf->writeHTML($html, true, false, true, false, '');
$pdf->Output('customer_invoice.pdf', 'I');
在创建 PDF 时,需要注意的是,大多数 HTML 到 PDF 转换器都是简单创建的,可以解释简单的内联 CSS 布局。我们使用表格来打印每个项目,这对于表格数据来说是可以的。它为布局提供了一个结构,并确保所有内容都正确对齐。
我们将建立管理系统来处理我们所有的采购。这是为了跟踪每个从我们网站购买东西的客户。它将由两页组成:
- 所有购买物品的客户的概述
- 能够查看客户购买的物品
我们还将在这些页面中添加一些功能,以便管理员更容易更改客户信息。
我们还将创建一个简单的htaccess apache 规则,以阻止其他人访问我们的管理站点,因为它包含高度敏感的数据。
让我们首先开始选择purchases
表中的所有数据:
<?php
//create an html variable for printing the html of our page:
$html = '<!DOCTYPE html><html><body>';
$table = 'purchases';
$results = $db->select_all($table);
//start a new table structure and set the headings of our table:
$html .= '<table><tr>
<th>Customer name</th>
<th>Email</th>
<th>Address</th>
<th>Total Purchase</th>
</tr>';
//loop through the results of our query:
while($row = $results->fetch_assoc()){
$html .= '<tr><td>'$row['customer_name'] . '</td>';
$html .= '<td>'$row['email'] . '</td>';
$html .= '<td>'$row['address'] . '</td>';
$html .= '<td>'$row['purchase_date'] . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
$html .= '</body></html>;
//print out the html
echo $html;
我们现在将添加一个链接到我们的客户数据的另一个视图。此视图将使管理员能够查看他们的所有购买。我们可以将第一页链接到客户购买的详细视图,方法是在客户名称上添加一个链接,将我们在$html
变量中添加客户名称的行更改为:
$html .= '<tr><td><a href="view_purchases.php?pid='.$row['id'] .'">'$row['customer_name'] . '</a></td>';
请注意,我们已经将$row['id']
作为 URL 的一部分。我们现在可以通过$_GET['pid']
值访问将要获取的数据的 ID 号。
让我们在新文件中创建查看客户购买物品的代码-view_purchases.php
:
<?php
//create an html variable for printing the html of our page:
$html = '<!DOCTYPE html><html><body>';
$table = 'purchases;
$column = 'id';
$purchase_id = $_GET['pid'];
$results = $db->read($table, $column, $purchase_id);
//outputs:
// SELECT * FROM purchases WHERE id = '$purchase_id';
//start a new table structure and set the headings of our table:
$html .= '<table><tr><th>Customer name</thth>Total Purchased</th></tr>';
//loop through the results of our query:
while($row = $results->fetch_assoc()){
$html .= '<tr><td>'$row['customer_name'] . '</td>';
$html .= '<tr><td>'$row['email'] . '</td>';
$html .= '<tr><td>'$row['address'] . '</td>';
$html .= '<tr><td>'$row['purchase_date'] . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
echo $html;
在前面的代码中,我们使用了$_GET['id']
变量来查找表中客户的确切购买情况。虽然我们可以使用客户名称从表purchases
中查找客户的购买,但这将假定客户只通过我们的系统购买了一次。此外,我们没有使用客户名称来确定有时是否有同名的客户。
在我们的例子中,通过使用表purchases
的主 ID,id
字段的选择确保我们选择的是特定的唯一购买。请注意,因为我们的数据库很简单,所以在本例中,我们可以只查询数据库中的一个表--purchases
表。
也许更好的实现是将purchases
表分为两个表——一个包含客户的详细信息,另一个包含购买的物品的详细信息。这样,如果同一客户退货,下次可以自动填写他们的详细信息,我们只需要将新购买的商品链接到他们的帐户。
在这种情况下,purchases
表将被简单地称为purchased_items
表,每个项目都将链接到一个客户 ID。客户详细信息将存储在一个customers
表中,其中包含他们的唯一地址、电子邮件和信用卡详细信息。
然后,您将能够向客户显示其购买历史记录。每次客户从商店购买时,都会记录交易日期,您必须按每个条目的日期和时间对历史进行排序。
太好了,我们完成了!
我们刚刚学习了如何构建一个简单的数据库抽象层,以及如何将其用于购物车。我们还学习了 Cookie 和使用 TCPDF 库生成发票。
在下一章中,我们将构建一个完全不同的东西,并在构建基于 PHP 的聊天系统时使用会话来保存用户的当前用户信息。