首先先吐槽下mysqli与mysql,前者是后者的改进版,我的ps不支持mysql相关函数,而且我看的是w3school上的教程,呵呵,w3school上的代码用的是旧版本的mysql函数,我去,让我一个个百mysqli系列函数的用法。。。
php5以上的版本,建议使用mysqli和PDO。有个网站,我刚发现的:http://www.runoob.com
mysqli和PDO各有各的优势。PDO应用于12中数据库,是一种通用的写法;而mysqli是专门针对mysql的。两者都是面向对象,而mysqli还提高了API接口。两者都支持预处理语句,预处理语句可以防止SQL注入,对于web项目的安全性是非常重要的。因为我现在专门开发mysql项目,故而就使用mysqli吧,PDO只了解即可。PDO的学习可以参考上面那个网址。
下面说mysqli操作数据库。
做个小目录:
1.连接数据库
2.关闭连接
3.创建数据库
4.创建表
5.插入数据
6.插入多条数据
7.预处理语句
8.读取数据
9.where
10.order by
11.update
12.delete
13.ODBC
连接数据库:
mysqli(面向对象)
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; // 创建连接 $conn = new mysqli($servername, $username, $password); // 检测连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully"; ?>
注意在以上面向对象的实例中 $connect_error 是在 PHP 5.2.9 和 5.3.0 中添加的。如果你需要兼容更早版本 请使用以下代码替换: // 检测连接 if (mysqli_connect_error()) { die("Database connection failed: " . mysqli_connect_error()); }
mysqli(面向过程)
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; // 创建连接 $conn = mysqli_connect($servername, $username, $password); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully"; ?>
关闭连接:
mysqli(面向对象)
$conn->close();
mysqli(面向过程)
mysqli_close($conn);
创建数据库:
CREATE DATABASE语句用于创建数据库:
mysqli面向对象:这里创建了tdb0.
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; // 创建连接 $conn = mysqli_connect($servername, $username, $password); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully<br>"; // Create database $sql = "CREATE DATABASE tdb0"; if ($conn->query($sql) === TRUE) { echo "Database created successfully"; } else { echo "Error creating database: " . $conn->error; } $conn->close(); ?>
注意: 当你创建一个新的数据库时,你必须为 mysqli 对象指定三个参数 (servername, username 和 password)。 Tip: 如果你使用其他端口(默认为3306),为数据库参数添加空字符串,如: new mysqli("localhost", "username", "password", "", port)
mysqli面向过程:
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; // 创建连接 $conn = mysqli_connect($servername, $username, $password); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // Create database $sql = "CREATE DATABASE tdb1"; if (mysqli_query($conn, $sql)) { echo "Database created successfully"; } else { echo "Error creating database: " . mysqli_error($conn); } mysqli_close($conn); ?>
创建表:
CREATE TABLE 语句用于创建 MySQL 表。
mysqli面向对象:
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; $dbname="jiu151231"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // sql to create table $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 "Error creating table: " . $conn->error; } $conn->close(); ?>
mysqli面向过程:
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; $dbname="jiu151231"; // 创建连接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } // sql to create table $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 (mysqli_query($conn, $sql)) { echo "Table MyGuests created successfully"; } else { echo "Error creating table: " . mysqli_error($conn); } mysqli_close($conn); ?>
上表中的注意事项:
数据类型指定列可以存储什么类型的数据。完整的数据类型请参考我们的 数据类型参考手册。
在设置了数据类型后,你可以为每个列指定其他选项的属性:
每个表都应该有一个主键(本列为 "id" 列),主键必须包含唯一的值。
插入数据:
以下为一些语法规则:
INSERT INTO 语句通常用于向 MySQL 表添加新的记录:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)
注意: 如果列设置 AUTO_INCREMENT (如 "id" 列) 或 TIMESTAMP (如 "reg_date" 列),,我们就不需要在 SQL 查询语句中指定值; MySQL 会自动为该列添加值。
mysqli面向对象:
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; $dbname="jiu151231"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')"; if ($conn->query($sql) === TRUE) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
mysqli面向过程:
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; $dbname="jiu151231"; // 创建连接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 检测连接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]')"; if (mysqli_query($conn, $sql)) { echo "New record created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
插入多条语句:
mysqli_multi_query() 函数可用来执行多条SQL语句。
mysqli面向对象:
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; $dbname="jiu151231"; // 创建链接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查链接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')"; if ($conn->multi_query($sql) === TRUE) { echo "New records created successfully"; } else { echo "Error: " . $sql . "<br>" . $conn->error; } $conn->close(); ?>
mysqli面向过程:
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; $dbname="jiu151231"; // 创建链接 $conn = mysqli_connect($servername, $username, $password, $dbname); // 检查链接 if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } $sql = "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('John', 'Doe', '[email protected]');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Mary', 'Moe', '[email protected]');"; $sql .= "INSERT INTO MyGuests (firstname, lastname, email) VALUES ('Julie', 'Dooley', '[email protected]')"; if (mysqli_multi_query($conn, $sql)) { echo "New records created successfully"; } else { echo "Error: " . $sql . "<br>" . mysqli_error($conn); } mysqli_close($conn); ?>
预处理语句用于执行多个相同的 SQL 语句,并且执行效率更高。
预处理语句的工作原理如下:
相比于直接执行SQL语句,预处理语句有两个主要优点:
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; $dbname="jiu151231"; // Create connection $conn = new mysqli($servername, $username, $password, $dbname); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } else { $sql = "INSERT INTO MyGuests 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 = '[email protected]'; mysqli_stmt_execute($stmt); $firstname = 'Mary'; $lastname = 'Moe'; $email = '[email protected]'; mysqli_stmt_execute($stmt); $firstname = 'Julie'; $lastname = 'Dooley'; $email = '[email protected]'; mysqli_stmt_execute($stmt); } } ?>
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; $dbname="jiu151231"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } // prepare and bind $stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES(?, ?, ?)"); $stmt->bind_param("sss", $firstname, $lastname, $email); // 设置参数并执行 $firstname = "John"; $lastname = "Doe"; $email = "[email protected]"; $stmt->execute(); $firstname = "Mary"; $lastname = "Moe"; $email = "[email protected]"; $stmt->execute(); $firstname = "Julie"; $lastname = "Dooley"; $email = "[email protected]"; $stmt->execute(); echo "New records created successfully"; $stmt->close(); $conn->close(); ?>
我们可以看到以上实例中使用模块化来处理问题。我们可以通过创建代码块实现更简单的读取和管理。
注意参数的绑定。让我们看下 mysqli_stmt_bind_param() 中的代码:
mysqli_stmt_bind_param($stmt, 'sss', $firstname, $lastname, $email);
该函数绑定参数查询并将参数传递给数据库。第二个参数是 "sss" 。以下列表展示了参数的类型。 s 字符告诉 mysql 参数是字符串。
This argument may be one of four types:
每个参数必须指定类型,来保证数据的安全性。通过类型的判断可以减少SQL注入漏洞带来的风险。
SELECT 语句用于从数据表中读取数据:
SELECT column_name(s) FROM table_name
mysqli面向对象:
<?php $servername = "127.0.0.1"; $username = "root"; $password = ""; $dbname="jiu151231"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检测连接 if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql); if ($result->num_rows > 0) { // 输出每行数据 while($row = $result->fetch_assoc()) { echo "<br> id: ". $row["id"]. " - Name: ". $row["firstname"]. " " . $row["lastname"]; } } else { echo "0 results"; } $conn->close(); ?>
where子句
WHERE 子句用于提取满足指定标准的的记录。
SELECT column_name(s)
FROM table_name
WHERE column_name operator value
<?php $con=mysqli_connect("example.com","peter","abc123","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . 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 关键词用于对记录集中的数据进行排序。
ORDER BY 关键词默认对记录进行升序排序。默认为ASC。
如果你想降序排序,请使用 DESC 关键字。
SELECT column_name(s)
FROM table_name
ORDER BY column_name(s) ASC|DESC
<?php $con=mysqli_connect("example.com","peter","abc123","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . 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); ?>
可以根据多个列进行排序。当按照多个列进行排序时,只有第一列的值相同时才使用第二列:
SELECT column_name(s)
FROM table_name
ORDER BY column1, column2
UPDATE 语句用于更新数据库表中已存在的记录。
UPDATE table_name SET column1=value, column2=value2,... WHERE some_column=some_value
注释:请注意 UPDATE 语法中的 WHERE 子句。WHERE 子句规定了哪些记录需要更新。如果您想省去 WHERE 子句,所有的记录都会被更新!
<?php $con=mysqli_connect("example.com","peter","abc123","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"UPDATE Persons SET Age=36 WHERE FirstName='Peter' AND LastName='Griffin'"); mysqli_close($con); ?>
DELETE FROM 语句用于从数据库表中删除记录。
DELETE FROM table_name
WHERE some_column = some_value
注释:请注意 DELETE 语法中的 WHERE 子句。WHERE 子句规定了哪些记录需要删除。如果您想省去 WHERE 子句,所有的记录都会被删除!
<?php $con=mysqli_connect("example.com","peter","abc123","my_db"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } mysqli_query($con,"DELETE FROM Persons WHERE LastName='Griffin'"); mysqli_close($con); ?>
ODBC 是一种应用程序编程接口(Application Programming Interface,API),使我们有能力连接到某个数据源(比如一个 MS Access 数据库)。
通过一个 ODBC 连接,您可以连接到您的网络中的任何计算机上的任何数据库,只要 ODBC 连接是可用的。
这是创建到达 MS Access 数据库的 ODBC 连接的方法:
请注意,必须在您的网站所在的计算机上完成这个配置。如果您的计算机上正在运行 Internet 信息服务(IIS),上面的指令将会生效,但是如果您的网站位于远程服务器,您必须拥有对该服务器的物理访问权限,或者请您的主机提供商为您建立 DSN。
odbc_connect() 函数用于连接到 ODBC 数据源。该函数有四个参数:数据源名、用户名、密码以及可选的指针类型。
odbc_exec() 函数用于执行 SQL 语句。
下面的实例创建了到达名为 northwind 的 DSN 的连接,没有用户名和密码。然后创建并执行一条 SQL 语句:
$conn=odbc_connect('northwind','',''); $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql);
odbc_fetch_row() 函数用于从结果集中返回记录。如果能够返回行,则函数返回 true,否则返回 false。
该函数有两个参数:ODBC 结果标识符和可选的行号:
odbc_fetch_row($rs)
odbc_result() 函数用于从记录中读取字段。该函数有两个参数:ODBC 结果标识符和字段编号或名称。
下面的代码行从记录中返回第一个字段的值:
$compname=odbc_result($rs,1);
下面的代码行返回名为 "CompanyName" 的字段的值:
$compname=odbc_result($rs,"CompanyName");
odbc_close() 函数用于关闭 ODBC 连接。
odbc_close($conn);
下面的实例展示了如何首先创建一个数据库连接,接着创建一个结果集,然后在 HTML 表格中显示数据。
<html> <body> <?php $conn=odbc_connect('northwind','',''); if (!$conn) {exit("Connection Failed: " . $conn);} $sql="SELECT * FROM customers"; $rs=odbc_exec($conn,$sql); if (!$rs) {exit("Error in 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>