[PHP] 07 - Json, XML and MySQL
前言
[Node.js] 09 - Connect with Database
SQL语句需要复习一遍:http://www.runoob.com/sql/sql-tutorial.html
MySQL
一、PHP 连接 MySQL
PHP 5 及以上版本建议使用以下方式连接 MySQL :
-
- MySQLi extension ("i" 意为 improved)
- PDO (PHP Data Objects)
- MySQLi - 面向对象
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } echo "连接成功"; ?>
# 关闭连接
$conn->close();
- MySQLi - 面向过程
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = mysqli_connect($servername, $username, $password); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "连接成功"; ?>
# 关闭连接
mysqli_close($conn);
- PDO - Only 面向对象
<?php $servername = "localhost"; $username = "username"; $password = "password"; try { $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password); echo "连接成功"; } catch(PDOException $e) { echo $e->getMessage(); } ?>
# 关闭连接
$conn = null;
- 连接与检测示范
try{ //解析config.ini文件,获取数据库连接参数 $config = parse_ini_file(realpath(dirname(__FILE__) . '/config/config.ini'));
//对mysqli类进行实例化 $mysqli = new mysqli($config['host'], $config['username'], $config['password'], $config['dbname']);
if(mysqli_connect_errno()){ // 判断是否成功连接上MySQL数据库 throw new Exception('数据库连接错误!'); // 如果连接错误,则抛出异常 }else{ echo '数据库连接成功!'; // 打印连接成功的提示 } }catch (Exception $e){ // 捕获异常 echo $e->getMessage(); // 打印异常信息 }
二、SQL 常用操作
- create 创建数据库
<?php $servername = "localhost"; $username = "username"; $password = "password"; // 创建连接 $conn = new mysqli($servername, $username, $password);
// 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 创建数据库 $sql = "CREATE DATABASE myDB"; if ($conn->query($sql) === TRUE) { echo "数据库创建成功"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); ?>
Goto: http://www.runoob.com/php/php-mysql-create.html
- create MySQL 表
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } --------------------------------------------------------------- // 使用 sql 创建数据表 $sql = "CREATE TABLE MyGuests ( id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, firstname VARCHAR(30) NOT NULL, lastname VARCHAR(30) NOT NULL, email VARCHAR(50), reg_date TIMESTAMP )"; if ($conn->query($sql) === TRUE) { echo "Table MyGuests created successfully"; } else { echo "创建数据表错误: " . $conn->error; } $conn->close(); ?>
- select 查询
Goto: PHP MySQL 读取数据
mysql> set names utf8; mysql> SELECT name FROM websites; +---------------+ | name | +---------------+ | Google | | 淘宝 | | 菜鸟教程 | | 微博 | | Facebook | | stackoverflow | +---------------+ 6 rows in set (0.00 sec)
- insert 插入数据
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com')"; if ($conn->query($sql) === TRUE) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
- insert 插入多条数据
注意变量sql后面的"点“。
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建链接 $conn = new mysqli($servername, $username, $password, $dbname);
// 检查链接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', 'john@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', 'mary@example.com');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', 'julie@example.com')"; if ($conn->multi_query($sql) === TRUE) { echo "新记录插入成功"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
- Where 子句
[有返回值] 从 "Persons" 表中选取所有 FirstName='Peter' 的行:
<?php $con=mysqli_connect("localhost","username","password","database");
// 检测连接 if (mysqli_connect_errno()) { echo "连接失败: " . mysqli_connect_error(); } $result = mysqli_query($con, "SELECT * FROM Persons WHERE FirstName='Peter'"); while($row = mysqli_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br>"; } ?>
- Order By 关键词
<?php $con=mysqli_connect("localhost","username","password","database");
// 检测连接 if (mysqli_connect_errno()) { echo "连接失败: " . mysqli_connect_error(); } $result = mysqli_query($con, "SELECT * FROM Persons ORDER BY age"); while($row = mysqli_fetch_array($result)) { echo $row['FirstName']; echo " " . $row['LastName']; echo " " . $row['Age']; echo "<br>"; } mysqli_close($con); ?>
- update 更新数据库
<?php $con=mysqli_connect("localhost","username","password","database");
// 检测连接 if (mysqli_connect_errno()) { echo "连接失败: " . mysqli_connect_error(); } mysqli_query($con,"UPDATE Persons SET Age=36 WHERE FirstName='Peter' AND LastName='Griffin'"); mysqli_close($con); ?>
- Delete 数据
<?php $con=mysqli_connect("localhost","username","password","database");
// 检测连接 if (mysqli_connect_errno()) { echo "连接失败: " . mysqli_connect_error(); } mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'"); mysqli_close($con); ?>
三、使用预处理语句
可以通过创建代码块实现更简单的读取和管理。
Goto: http://www.runoob.com/php/php-mysql-insert-multiple.html
<?php $servername = "localhost"; $username = "username"; $password = "password"; $dbname = "myDB"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname);
// 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error);
} else { $sql = "INSERT INTO MyGuests(firstname, lastname, email) VALUES(?, ?, ?)"; // 为 mysqli_stmt_prepare() 初始化 statement 对象 $stmt = mysqli_stmt_init($conn); //预处理语句 if (mysqli_stmt_prepare($stmt, $sql)) { // 绑定参数 mysqli_stmt_bind_param($stmt, 'sss', $firstname, $lastname, $email); // 设置参数并执行 $firstname = 'John'; $lastname = 'Doe'; $email = 'john@example.com'; mysqli_stmt_execute($stmt); $firstname = 'Mary'; $lastname = 'Moe'; $email = 'mary@example.com'; mysqli_stmt_execute($stmt); $firstname = 'Julie'; $lastname = 'Dooley'; $email = 'julie@example.com'; mysqli_stmt_execute($stmt); } } ?>
Goto: PHP MySQL 预处理语句
/* IMPLEMENT */
四、PHP 数据库 ODBC
ODBC 是一种应用程序编程接口(Application Programming Interface,API),使我们有能力连接到某个数据源(比如一个 MS Access 数据库)。
通过一个 ODBC 连接,您可以连接到您的网络中的任何计算机上的任何数据库,只要 ODBC 连接是可用的。
- 首先创建一个数据库连接,
- 接着创建一个结果集,
- 然后在 HTML 表格中显示数据
<html> <body> <?php $conn=odbc_connect('northwind','',''); if (!$conn) { exit("连接失败: " . $conn); } $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); if (!$rs) { exit("SQL 语句错误"); }
echo "<table><tr>"; echo "<th>Companyname</th>"; echo "<th>Contactname</th></tr>"; while (odbc_fetch_row($rs)) { $compname=odbc_result($rs,"CompanyName"); $conname=odbc_result($rs,"ContactName"); echo "<tr><td>$compname</td>"; echo "<td>$conname</td></tr>"; }
odbc_close($conn); echo "</table>"; ?> </body> </html>
JSON
json_encode | 对变量进行 JSON 编码 |
json_decode | 对 JSON 格式的字符串进行解码,转换为 PHP 变量 |
json_last_error | 返回最后发生的错误 |
一、编码
<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?>
Array ----> Json
{"a":1,"b":2,"c":3,"d":4,"e":5}
<?php class Emp { public $name = ""; public $hobbies = ""; public $birthdate = ""; } $e = new Emp(); $e->name = "sachin"; $e->hobbies = "sports"; $e->birthdate = date('m/d/Y h:i:s a', "8/5/1974 12:20:03 p"); $e->birthdate = date('m/d/Y h:i:s a', strtotime("8/5/1974 12:20:03")); echo json_encode($e); ?>
对象 ----> Json {"name":"sachin","hobbies":"sports","birthdate":"08\/05\/1974 12:20:03 pm"}
二、解码
<?php $json = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; var_dump(json_decode($json)); // 返回对象,默认是false var_dump(json_decode($json, true)); // 返回数组 ?>
----------------------------------------------------------------
返回结果:
# 对象
object(stdClass)#1 (5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
# 数组
array(5) {
["a"] => int(1)
["b"] => int(2)
["c"] => int(3)
["d"] => int(4)
["e"] => int(5)
}
XML
Ref: XML 教程
一、Expat 是什么?
如需读取和更新 - 创建和处理 - 一个 XML 文档,您需要 XML 解析器。
有两种基本的 XML 解析器类型:
-
- 基于树的解析器:这种解析器把 XML 文档转换为树型结构。它分析整篇文档,并提供了对树中元素的访问,例如文档对象模型 (DOM)。
- 基于事件的解析器:将 XML 文档视为一系列的事件。当某个具体的事件发生时,解析器会调用函数来处理。
Expat 解析器是基于事件的解析器。
基于事件的解析器集中在 XML 文档的内容,而不是它们的结构。
正因为如此,基于事件的解析器能够比基于树的解析器更快地访问数据。
- 对XML的要求
Expat 是不检查有效性的解析器,忽略任何 DTD。
作为一款基于事件、非验证的 XML 解析器,Expat 快速且轻巧,十分适合 PHP 的 Web 应用程序。
注释:XML 文档必须形式良好,否则 Expat 会生成错误。
二、解析 XML
- XML Expat 解析器
[1] 解析的对象
<?xml version="1.0" encoding="ISO-8859-1"?> <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note>
[2] 解析出的内容
-- Note --
To: Tove
From: Jani
Heading: Reminder
Message: Don't forget me this weekend!
[3] php 解析代码
<?php // 1. Initialize the XML parser $parser=xml_parser_create(); // 2. Function to use at the start of an element function start($parser, $element_name, $element_attrs) { switch($element_name) { case "NOTE": echo "-- Note --<br>"; break; case "TO": echo "To: "; break; case "FROM": echo "From: "; break; case "HEADING": echo "Heading: "; break; case "BODY": echo "Message: "; } } //Function to use at the end of an element function stop($parser,$element_name) { echo "<br>"; } //Function to use when finding character data function char($parser,$data) { echo $data; } //Specify element handler xml_set_element_handler($parser,"start","stop"); //Specify data handler xml_set_character_data_handler($parser,"char"); //Open XML file $fp=fopen("test.xml","r"); //Read data while ($data=fread($fp,4096)) { xml_parse($parser,$data,feof($fp)) or die (sprintf("XML Error: %s at line %d", xml_error_string(xml_get_error_code($parser)), xml_get_current_line_number($parser))); } //Free the XML parser xml_parser_free($parser); ?>
工作原理:
- 通过 xml_parser_create() 函数初始化 XML 解析器
- 创建配合不同事件处理程序的的函数
- 添加 xml_set_element_handler() 函数来定义,当解析器遇到开始和结束标签时执行哪个函数
- 添加 xml_set_character_data_handler() 函数来定义,当解析器遇到字符数据时执行哪个函数
- 通过 xml_parse() 函数来解析文件 "test.xml"
- 万一有错误的话,添加 xml_error_string() 函数把 XML 错误转换为文本说明
- 调用 xml_parser_free() 函数来释放分配给 xml_parser_create() 函数的内存
- PHP XML DOM
W3C DOM 被分为不同的部分(Core, XML 和 HTML)和不同的级别(DOM Level 1/2/3):
- Core DOM - 为任何结构化文档定义标准的对象集
- XML DOM - 为 XML 文档定义标准的对象集
- HTML DOM - 为 HTML 文档定义标准的对象集
- PHP SimpleXML
PHP SimpleXML 处理最普通的 XML 任务,其余的任务则交由其它扩展处理。
SimpleXML 是 PHP 5 中的新特性。
SimpleXML 扩展提供了一种获取 XML 元素的名称和文本的简单方式。
与 DOM 或 Expat 解析器相比,SimpleXML 仅仅用几行代码就可以从 XML 元素中读取文本数据。
Goto: http://www.runoob.com/php/php-xml-simplexml.html