数据库连接
实例
<?php /医院 * 连接数据库 */ //1.连接参数 $db_host = 'localhost'; $db_user = 'root'; $db_pass = 'root'; $db_name = 'php'; $db_charset = 'utf8'; //2.连接数据库服务器,并返回mysqli对象 $mysqli = @new mysqli($db_host,$db_user,$db_pass,$db_name); //3.检测是否连接成功 if ($mysqli->connect_errno) { exit('连接错误'.$mysqli->connect_errno.':'.$mysqli->connect_error); } //4.设置客户端默认字符编码集 $mysqli->set_charset($db_charset);
运行实例 »
点击 "运行实例" 按钮查看在线实例
mysql面向对象更新操作:
更新前:
实例
<?php //1.连接数据库 require 'conndb.php'; //2.准备SQL语句 $sql = "UPDATE staff SET salary=? WHERE staff_id=?"; //3.创建STMT预处理对象 $stmt = $mysqli->stmt_init(); //4.检测预处理SQL语句 if ($stmt->prepare($sql)) { //用二维数组来保存要添加的记录 $data[] = ['salary'=> '5000','staff_id'=>10]; $data[] = ['salary'=> '6000','staff_id'=>11]; $data[] = ['salary'=> '7000','staff_id'=>12]; //绑定参数到预处理SQL语句 $stmt->bind_param('ii',$salary,$staff_id); foreach ($data as $staff) { //准备要插入的数据 $salary = $staff['salary']; $staff_id = $staff['staff_id']; //执行预处理语句 $stmt->execute(); //检测运行结果 if ($stmt->affected_rows > 0 ){ echo '<br>成功更新'.$stmt->affected_rows.'条记录'; } else { echo '<br>没有更新记录'; } } //5.注销stmt对象 $stmt->close(); } else { //返回错误信息 exit($stmt->errno.':'.$stmt->error); } //6. 关闭数据库连接 $mysqli->close();
运行实例 »
点击 "运行实例" 按钮查看在线实例
mysql面向对象删除操作:
实例
<?php //1.连接数据库 require 'conndb.php'; //2.准备SQL语句 $sql = "DELETE FROM staff WHERE staff_id=?"; //3.创建STMT预处理对象 $stmt = $mysqli->stmt_init(); //4.检测预处理SQL语句 if ($stmt->prepare($sql)) { //用二维数组来保存要添加的记录 $data[] = ['staff_id'=>10]; $data[] = ['staff_id'=>11]; $data[] = ['staff_id'=>12]; //绑定参数到预处理SQL语句 $stmt->bind_param('i',$staff_id); foreach ($data as $staff) { //准备要插入的数据 $staff_id = $staff['staff_id']; //执行预处理语句 $stmt->execute(); //检测运行结果 if ($stmt->affected_rows > 0 ){ echo '<br>成功删除'.$stmt->affected_rows.'条记录'; } else { echo '<br>没有删除记录'; } } //5.注销stmt对象 $stmt->close(); } else { //返回错误信息 exit($stmt->errno.':'.$stmt->error); } //6. 关闭数据库连接 $mysqli->close();
运行实例 »
点击 "运行实例" 按钮查看在线实例