MySQLi扩展

DML语句:连接且查询
<?php
// header('Content-Type:text/html;charset=utf-8');
/* 
@param string $host 主机
@param string $user 用户名
@param string $passwd 密码
@param string $dbname 数据库
@param int $port 端口
 */
$mySQLi = new MySQLi('localhost','root','123456','test',3306);
# 判断连接是否有误
if($mySQLi->connect_errno){
	die('连接失败,错误信息:'.$mySQLi->connect_error);
}
# 设置编码
$mySQLi->set_charset("utf8");
# 编写SQL语句
$sql = "select * from user";
# 查询SQL语句
$res = $mySQLi->query($sql);
# 获取返回结果
while($row = $res->fetch_assoc()){
	$rows[] = $row;
}

echo '<pre>';
var_dump($rows);

# 释放结果集资源
$res->free();
# 关闭连接资源
$mySQLi->close();

DQL 增删改
<?php
/* 
@param string $host 主机
@param string $user 用户名
@param string $passwd 密码
@param string $dbname 数据库
@param int $port 端口
 */
$mySQLi = new MySQLi('localhost','root','123456','test',3306);
# 判断连接是否有误
if($mySQLi->connect_errno){
	die('连接失败,错误信息:'.$mySQLi->connect_error);
}
# 设置编码
$mySQLi->set_charset("utf8");
# 编写SQL语句--增
$sql = "insert into user values(null,'root',md5('1234600'),current_date())";
# 编写SQL语句--删
$sql_another = "delete from user where id = 1";
# 编写SQL语句--改
$sql_other = "update user set username = 'master' where id = 2";
# 执行SQL语句
$res = $mySQLi->query($sql);
$res_another = $mySQLi->query($sql_another);
$res_other = $mySQLi->query($sql_other);
# 判断执行结果
if($res){
	echo '执行成功';
}else{
	echo '错误sql语句:' . $sql;
	echo '<br />错误信息:' . $mySQLi->error;
}
# 判断删改操作是否有受影响数据
if($res_another){
	if($mySQLi->affected_rows > 0){
		echo '<br />发现有受影响行';
	}else{
		echo '<br />无数据被修改';
	}
}else{
	echo '错误sql语句:' . $sql_another;
	echo '<br />错误信息:' . $mySQLi->error;
}

if($res_other){
	if($mySQLi->affected_rows > 0){
		echo '<br />发现有受影响行';
	}else{
		echo '<br />无数据被修改';
	}
}else{
	echo '错误sql语句:' . $sql_other;
	echo '<br />错误信息:' . $mySQLi->error;
}

猜你喜欢

转载自blog.csdn.net/qq_36436407/article/details/79459939