- 链接数据库
- 判断是否链接成功
- 选择数据库
- 设置字符集
- 准备sql语句
- 执行sql语句
- 处理数据
- 释放资源关闭连接
一、连接数据库
通过mysqli连接数据库,我们需要提供host地址,用户名和密码。
主要是通过mysqli_connect进行操作。
1 <?php 2 3 $link = mysqli_connect("localhost","root","123456"); // mysql host地址 mysql用户 mysql密码 4 5 print_r($link); 6 7 /* 8 输出结果: 9 mysqli Object ( [affected_rows] => 0 [client_info] => mysqlnd 5.0.12-dev - 20150407 - $Id: b396954eeb2d1d9ed7902b8bae237b287f21ad9e $ [client_version] => 50012 [connect_errno] => 0 [connect_error] => [errno] => 0 [error] => [error_list] => Array ( ) [field_count] => 0 [host_info] => localhost via TCP/IP [info] => [insert_id] => 0 [server_info] => 5.5.53 [server_version] => 50553 [stat] => Uptime: 7551 Threads: 1 Questions: 1902 Slow queries: 0 Opens: 42 Flush tables: 1 Open tables: 0 Queries per second avg: 0.251 [sqlstate] => 00000 [protocol_version] => 10 [thread_id] => 93 [warning_count] => 0 ) 10 */
二、判断是否链接成功
主要是通过下面两个方法来判断:
mysqli_connect_errno 连接错误号
mysqli_connect_error 连接错误信息
1 // 判断是否链接成功 2 if ($link) { 3 echo "Mysql connect success!"; 4 }else { 5 exit('error('.mysqli_connect_errno().'):'.mysqli_connect_error()); 6 }
三、选择用于数据库查询的默认数据库
选择数据库主要使用下面的方法:
选择用于数据库查询的默认数据库:mysqli_select_db
执行错误号:mysqli_errno
执行错误信息:mysqli_error
1 // 选择即将查询的数据库 2 $info = mysqli_select_db($link,"loginuser"); 3 // 判断是否选择数据库成功 4 if (!$info){ 5 echo 'error('.mysqli_errno($link).'):'.mysqli_error($link); 6 mysqli_close($link); 7 die; 8 }
四、设置字符集
设置字符集主要通过下面的方法进行设置:mysqli_set_charset()
-
// 设置字符集
-
mysqli_set_charset($link,'utf8');
五、准备sql语句
准备符合mysql语法的sql语句。
-
// 准备sql语句
-
$sql = "select * from userinfo;";
六、执行sql语句
执行预设好的sql语句,通过mysqli_query()方法。查询成功后返回一个mysqli_result 对象。
1 // 执行sql语句 ,返回一个mysqli_result 对象 2 $result = mysqli_query($link,$sql); 3 // 可以判断是否执行成功 4 if($result && mysqli_num_rows($result)) { 5 // 执行成功 6 echo "操作成功!"; 7 }
七、处理数据
处理数据可以通过下面的三个方法:
mysqli_fetch_row:获取一条数据的索引数组
mysqli_fetch_assoc:获取一条数据的关联数组
mysqli_fetch_array:获取一条数据的指定数组
1 // 操作数据 2 $info1 = mysqli_fetch_row($result); // 从结果集中取出一行数据作为数组返回 3 print_r($info1);// Array ( [0] => 1 [1] => С [2] => 123456 [3] => 2018-06-09 ) 4 $info2 = mysqli_fetch_assoc($result); // 从结果集中取出一条数据作为关联数组返回 5 print_r($info2);// Array ( [id] => 2 [name] => xiaoming [passwd] => 123456 [logindate] => 2018 ) 6 $info3 = mysqli_fetch_array($result);//函数从结果集中取得一行作为关联数组,或数字数组,或二者兼有,返回根据从结果集取得的行生成的数组,如果没有更多行则返回 false。 7 print_r($info3);//Array ( [0] => 3 [id] => 3 [1] => 张三 [name] => 张三 [2] => 123456 [passwd] => 123456 [3] => 2018 [logindate] => 2018 )
八、释放资源,关闭连接
在我们使用完毕之后,需要将资源释放,避免浪费性能。
mysqli_free_result($result);
mysqli_close($link);
1 // 释放资源,关闭连接 2 mysqli_free_result($result); // 释放资源 3 mysqli_close($link); // 关闭连接
完整代码:
1 <?php 2 3 $link = mysqli_connect("localhost","root","123456"); // mysql host地址 mysql用户 mysql密码 4 5 // 判断是否链接成功 6 if ($link) { 7 echo "Mysql connect success!"; 8 }else { 9 exit('error('.mysqli_connect_errno().'):'.mysqli_connect_error()); 10 } 11 12 // 选择即将查询的数据库 13 $info = mysqli_select_db($link,"loginuser"); 14 // 判断是否选择数据库成功 15 if (!$info){ 16 echo 'error('.mysqli_errno($link).'):'.mysqli_error($link); 17 mysqli_close($link); 18 die; 19 } 20 // 设置字符集 21 mysqli_set_charset($link,'utf8'); 22 // 准备sql语句 23 $sql = "select * from userinfo;"; 24 // 执行sql语句 ,返回一个mysqli_result 对象 25 $result = mysqli_query($link,$sql); 26 // 可以判断是否执行成功 27 if($result && mysqli_num_rows($result)) { 28 // 执行成功 29 echo "操作成功!"; 30 } 31 // 操作数据 32 $info1 = mysqli_fetch_row($result); // 从结果集中取出一行数据作为数组返回 33 print_r($info1);// Array ( [0] => 1 [1] => С [2] => 123456 [3] => 2018-06-09 ) 34 $info2 = mysqli_fetch_assoc($result); // 从结果集中取出一条数据作为关联数组返回 35 print_r($info2);// Array ( [id] => 2 [name] => xiaoming [passwd] => 123456 [logindate] => 2018 ) 36 $info3 = mysqli_fetch_array($result);//函数从结果集中取得一行作为关联数组,或数字数组,或二者兼有,返回根据从结果集取得的行生成的数组,如果没有更多行则返回 false。 37 print_r($info3);//Array ( [0] => 3 [id] => 3 [1] => 张三 [name] => 张三 [2] => 123456 [passwd] => 123456 [3] => 2018 [logindate] => 2018 ) 38 // 释放资源,关闭连接 39 mysqli_free_result($result); // 释放资源 40 mysqli_close($link); // 关闭连接
Tip:在本文当中只是提到了常用的方法,如果想要学习其他的方法,可以参考官方文档:http://php.net/manual/zh/book.mysqli.php。
Mysqli 以面向对象的形式连接操作mysql
上面的代码中,我们操作mysql是使用的mysqli的面向过程的写法,下面通过代码来演示一下mysqli的面向对象的使用方式:
1 <?php 2 3 // mysqli 面向对象操作mysql 4 5 // 基础数据库信息 6 $host = "localhost"; 7 $database = "loginuser"; 8 $username = "root"; 9 $password = "123456"; 10 $selectName = "张三"; // 要查找的用户名 11 $insertName = "testname"; 12 13 // 创建对象,打开连接 14 $mysqli = new mysqli($host,$username,$password,$database); 15 // 设置编码 16 if(!$mysqli->set_charset('utf8')){ 17 printf("Error loading character set utf8: %s\n", $mysqli->error); 18 }else{ 19 printf("Current character set: %s\n", $mysqli->character_set_name()); 20 } 21 22 // 诊断连接错误 23 if(mysqli_connect_errno()){ 24 die("could not connect to the database.\n" . mysqli_connect_error()); 25 } 26 // 选择数据库 27 $selectDb = $mysqli->select_db($database); // 选择数据库 28 if(!$selectDb){ // 判断是否选择成功 29 die("could not to the database\n" . mysql_error()); 30 } 31 // 进行查询操作 32 //mysqli对prepare的支持对于大访问量的网站是很有好处的,它极大地降低了系统开销,而且保证了创建查询的稳定性和安全性 33 if($stmt = $mysqli->prepare("select * from user where name=?")){ // prepare预查询 ,?是个通配符,可以用在任何有文字的数据 34 $stmt->bind_param("s",$selectName); // 第一个参数是绑定类型,"s"是指一个字符串,也可以是"i",指的是int。也可以是"db", d代表双精度以及浮点类型,而b代表blob类型,第二个参数是变量 35 $stmt->execute(); 36 $stmt->bind_result($name,$age); 37 38 while($stmt->fetch()){ 39 echo "Name:$name Age:$age \n"; 40 } 41 42 $stmt->close(); 43 } 44 45 //添加记录 46 if ($insertStmt = $mysqli->prepare("insert into user(name, age) values(?, 18)")) { 47 /* bind parameters for markers */ 48 $insertStmt->bind_param("s", $insertName); 49 /* execute query */ 50 $insertStmt->execute(); 51 echo $insertStmt->affected_rows . "\n"; 52 /* close statement */ 53 $insertStmt->close(); 54 } 55 56 //更新记录 57 if ($updateStmt = $mysqli->prepare("update user set age = 19 where name=?")) { 58 /* bind parameters for markers */ 59 $updateStmt->bind_param("s", $insertName); 60 /* execute query */ 61 $updateStmt->execute(); 62 echo $updateStmt->affected_rows . "\n"; 63 /* close statement */ 64 $updateStmt->close(); 65 } 66 67 //删除记录 68 $result = $mysqli->query("delete from user where age = 19"); 69 echo $result . "\n"; 70 71 $mysqli->close();//关闭连接