连接MySQLi有两种风格:
-
面向对象风格(推荐)
-
过程化风格
面向对象风格: 1
<?php
2
3$mysqli = new mysqli('localhost', 'root', '123456', 'test_laravel');
4
5if ($mysqli->connect_error) {
6 die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
7}
8
9$result = $mysqli->query('select * from articles');
10$row = $result->fetch_array(MYSQLI_ASSOC);
11print_r($row);
12
13// 关闭mysql连接
14$mysqli->close();
15
运行:
1Array
2(
3 [id] => 1
4 [title] => My new title
5 [body] => First Body
6 [created_at] => 2017-05-22 11:10:20
7 [updated_at] => 2017-05-22 11:30:58
8 [published_at] => 2017-05-22 11:10:00
9 [excerpt] =>
10)
fetch_array方法如果不带参数的话,则默认是MYSQLI_BOTH,输出是这样的:
1(
2 [0] => 1
3 [id] => 1
4 [1] => My new title
5 [title] => My new title
6 [2] => First Body
7 [body] => First Body
8 [3] => 2017-05-22 11:10:20
9 [created_at] => 2017-05-22 11:10:20
10 [4] => 2017-05-22 11:30:58
11 [updated_at] => 2017-05-22 11:30:58
12 [5] => 2017-05-22 11:10:00
13 [published_at] => 2017-05-22 11:10:00
14 [6] =>
15 [excerpt] =>
16)
也可以选择MYSQLI_NUM
1Array
2(
3 [0] => 1
4 [1] => My new title
5 [2] => First Body
6 [3] => 2017-05-22 11:10:20
7 [4] => 2017-05-22 11:30:58
8 [5] => 2017-05-22 11:10:00
9 [6] =>
10)
一般来说,选择MySQLI_ASSOC
面向过程化风格: 1
<?php
2
3$mysqli = mysqli_connect('localhost', 'root', '123456', 'test_laravel');
4
5if (mysqli_connect_error()) {
6 die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
7}
8
9$result = mysqli_query($mysqli, 'select * from articles');
10$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
11print_r($row);
12
13// 关闭mysql连接
14mysqli_close($mysqli);
15
运行和上面一致。
使用PDO连接mysql: 1
<?php
2
3try {
4 $PDO = new PDO('mysql:host=localhost;dbname=test_laravel', 'root', '123456');
5 $result = $PDO->query('select * from articles');
6 $row = $result->fetch(PDO::FETCH_ASSOC);
7 print_r($row);
8
9 // 关闭mysqi连接
10 $PDO = null;
11} catch (PDOException $e) {
12 die('Connection failed: ' . $e->getMessage());
13}
PDO的fetch方法不带参数的话,默认是:PDO::FETCH_BOTH,也可以PDO::FETCH_NUM和PDO::FETCH_ASSOC等,一般来说选择PDO::FETCH_ASSOC即可。
总结:使用PDO或者是MySQLi都是可以的,但网上更推荐使用PDO来连接数据库,这是因为PDO支持12种不同的数据库驱动程序,而MySQLi只能支持MySQL,另外PDO的性能也更高。