起步
由于mysql连接方式被废除,在php7中要使用mysql_connect()还需要额外下载组件。
使用mysqli有面向过程和面向对象两种方式。
mysqli提供了三个类:
● mysqli 连接相关的
● mysqli_result 处理结果集
● mysqli_stmt 预处理类
数据库连接
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?php
$db_host = 'localhost' ;
$db_name = 'test' ;
$db_user = 'root' ;
$db_pwd = '' ;
$mysqli = new mysqli( $db_host , $db_user , $db_pwd , $db_name );
if (mysqli_connect_error()){
echo mysqli_connect_error();
}
$mysqli ->set_charset( "utf8" );
$mysqli ->close();
$mysqli = mysqli_connect( $db_host , $db_user , $db_pwd , $db_name );
if (! $mysqli ){
echo mysqli_connect_error();
}
mysqli_close( $mysqli );
?>
|
数据库查询
通用:执行sql语句都可用query(sql),执行失败会返回false,select成功则返回结果集对象,其他返回true,只要不是false就说明sql语句执行成功了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?php
$sql = "insert into table_name (`name`, `address`) values ('xiaoming', 'adddddrrreess')" ;
$result = $mysqli ->query( $sql );
$sql = "delete from table_name where name='xiaoming'" ;
$result = $mysqli ->query( $sql );
if ( $result === false){
echo $mysqli ->error;
echo $mysqli ->errno;
}
echo $mysqli ->num_rows;
echo $mysqli ->insert_id;
$mysqli ->close();
|
有结果集
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<?php
$sql = "select * from table_name" ;
$result = $mysqli ->query( $sql );
if ( $result === false){
echo $mysqli ->error;
echo $mysqli ->errno;
}
echo $result ->num_rows;
echo $result ->field_count;
$field_info_arr = $result ->fetch_fields();
while ( $row = $result ->fetch_assoc()){
echo $row [ 'name' ];
echo $row [ 'address' ];
}
$data = $result ->fetch_all(MYSQLI_ASSOC);
$mysqli ->close();
|
预处理示例
预处理能有效的防止sql注入的产生,mysqli_stmt是预处理类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
<?php
$sql = "insert inro table_name ('name','address') values (?,?)" ;
$stmt = $mysqli ->prepare( $sql );
$name = "xiaoming" ;
$address = "adddressss" ;
$stmt ->bind_param( "ss" , $name , $address );
$stmt ->execute();
echo $stmt ->insert_id;
echo $stmt ->affected_rows;
echo $stmt ->errno;
echo $stmt ->error;
$stmt ->close();
$mysqli ->close();
下面示例select的预处理
$sql = "select * from table_name where id<?" ;
$stmt = $mysqli ->prepare( $sql );
$id = 30;
$stmt ->bind_param( "i" , $id );
$stmt ->execute();
$result = $stmt ->get_result();
$data = $result ->fetch_all(MYSQLI_ASSOC);
$result ->close();
$mysqli ->close();
|
一次执行多条sql语句multiquery(不推荐),执行结果不是结果集,affectd_rows是最后影响的条数
1
2
3
4
5
6
7
8
9
10
11
12
|
<?php
$sql_arr = array (
"insert into table_name (`name`,`address`) values ('xiaoming','a')" ,
"insert into table_name (`name`,`address`) values ('xiaohong','a')" ,
'delete from table_name where id=23' ,
);
$sql = implode( ';' , $sql_arr );
$result = $mysqli ->multi_query( $sql );
if ( $result === false){
echo $mysqli ->error;
}
$mysqli ->close();
|
明确的学习思路能更高效的学习
点此加入该群学习