1.连接MySQL数据库<?php
$mysqli = new mysqli("localhost", "root", "123456", "mydb");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: " . $mysqli->connect_error;
}else{
echo "success connected!";
}
2.执行DDL语句
可以通过上面创建的$mysqli对象的query方法来执行sql语句,sql语句作为一个字符串传给query()方法
query()支持将语句执行的执行结果缓存到客户端,与real_query()和multi_query()方法相比,更常用。$mysqli->query("drop table if exists test");
$mysqli->query("create table test(id int primary key auto_increment)");
$mysqli->query("insert into test values(1)");
如果需要连续执行多条sql语句则必须要使用multi_query(),多条sql语句使用分号隔开。$sql="insert into test values(400);select * from test;";
$mysqli->multi_query($sql);
$res = $mysqli->store_result();
var_dump($res->fetch_all(MYSQLI_ASSOC));
$res->close();
3.执行查询语句
$mysqli对象通过query方法执行查询语句返回一个结果对象$res,该对象缓存了查询的结果,通过$res对象的fetch_assoc()方法可以一次返回一行数据,该行数据被存到一个索引数组当中,通过数据字段名作为索引可以取得对应的数据$res = $mysqli->query("select * from test");
if($res != null){
while($row = $res->fetch_assoc()){
echo $row["id"];
echo gettype($row["id"]);//string类型
}
}
注意mysqli的query()方法执行的是没有预编译的语句,通过query()返回的结果默认都是字符串类型(string),如果想要使得结果返回正确的PHP的数值类型,可以为mysqli添加属性MYSQLI_OPT_INT_AND_FLOAT_NATIVE$mysqli->options(MYSQLI_OPT_INT_AND_FLOAT_NATIVE, 1);
4.执行预编译语句
通过执行预编译语句,可以为sql语句动态指定参数。$stmt = $mysqli->prepare("insert into test values(?)");//预编译sql语句
$id = 9;
$stmt->bind_param("i",$id);//绑定参数
$stmt->execute();//执行sql语句
$stmt->close();//关闭预编译语句,释放资源,切记不要忘了执行
与非预编译执行的sql语句相比,通过预编译执行的语句的查询结果返回的值会自动转为正确的类型(而非都是string类型)。$stmt = $mysqli->prepare("select * from test");
$stmt->execute();
$res = $stmt->get_result();//获取查询结果
while($row = $res->fetch_assoc()){
echo $row["id"];
echo gettype($row["id"]);//integer 而不是string
}
使用预编译的sql语句可以有效的防止sql注入,增加对数据库操作的安全性。
5.执行存储过程$mysqli->query("create procedure p(IN id_val int) begin insert into test(id) values(id_val);END;");
$mysqli->query("call p(10)");//执行存储过程
$res = $mysqli->query("select * from test");
var_dump($res->fetch_all());
6.执行事务
MySQL是否支持事务取决于它的存储引擎,从MySQL5.5开始,默认的存储引擎改为InnoDB,InnoDB完全支持事务的ACID特性。$mysqli->autocommit(false);//设置自动提交事务为false
$mysqli->query("insert into test values(100)");
$mysqli->rollback();//回滚事务,100没有插入
$mysqli->query("insert into test values(101)");
$mysqli->commit();//提交事务,仅仅插入了101
7.元数据Metadata
元数据用来描述结果集中的列,通过mysqli_result接口可以获得元数据的信息$res = $mysqli->query("select * from test");
var_dump($res->fetch_fields());
还有很多方法没有涉及到,这里仅仅涉及了常用的一些方法,要了解更多方法可以自行查找PHP Mannual。