Blogger Information
Blog 61
fans 0
comment 0
visits 63193
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
MySQL面向对象预处理方式来实现更新操作
Pengsir
Original
882 people have browsed it

MySQL面向对象方式连接数据库:

实例

<?php
/
 * MySQL面向对象方式连接数据库
 */
header("content-type:text/html;charset=utf8");//php的编码
//1.连接参数
$db_host='127.0.0.1';//linux/MacOS数据库服务器主机名用:localhost
$db_user='root';
$db_pass='root';
$db_name='php';
$db_char='utf8';

//2.连接数据库服务器
$mysqli = @new mysqli($db_host,$db_user,$db_pass,$db_name);

//3.检测是否连接成功
if($mysqli->connect_errno){
    exit('连接错误'.$mysqli->connect_errno.':'.$mysqli->connect_error);
}
echo '连接成功';
//4.设置客户端的默认字符编码集合
$mysqli->set_charset($db_char);//数据库的编码

运行实例 »

点击 "运行实例" 按钮查看在线实例

MySQL面向对象预处理方式来实现更新操作:

实例

<?php
/*
 * MySQL面向对象预处理方式来实现更新操作
 */
//1.连接数据库
require 'dbconnect.php';

//2.准备sql语句
$sql="UPDATE user SET user_name=?,email=? WHERE user_id=1";

//3.创建出预处理stmt对象
$stmt=$mysqli->stmt_init();

//4.检测stmt,预处理的SQL语句对象
if($stmt->prepare($sql)){
    //创建二维数组来保存要添加的数据
    $data[]=['user_name'=>'天刑道者','email'=>'php@qq.com'];


//4.绑定参数
$stmt->bind_param('ss',$user_name,$email);
foreach ($data as $datum) {
    $user_name = $datum['user_name'];
    $email = $datum['email'];

//5.执行SQL语句
    $stmt->execute();
    if ($stmt->affected_rows > 0) {
        echo '<br>更新成功' . $stmt->affected_rows . '条记录,id:' . $stmt->insert_id;
    } else {
        echo '<br>更新失败';
    }
}
}else{//错误处理
    exit($stmt->errno.':'.$stmt->error);
}
//6.关闭连接
$mysqli->close();

运行实例 »

点击 "运行实例" 按钮查看在线实例

运行效果图:

mysql面向对象预处理更新数据.png

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post