MySQLi预处理

预处理是先提交SQL语句到服务端执行预编译,客户端执行SQL语句时,只需要上传输入参数即可,如果涉及多次读取和存储,效率高于普通SQL执行操作。

增删改

<?php
$sql = '????'; //暂时不用赋值,用?代替
$mysqli -> prepare($sql); //创建预编译对象
$stmt ->bind_param(); //参数赋值 string-s int-i double-d bool-b
$stmt -> execute(); //执行代码

实例

header("content-type:text/html;charset=utf-8");
$mysqli = new mysqli('127.0.0.1','root','root','mysqli');
$mysqli -> query('set names utf8' );
$sql = "INSERT INTO users(name,money) VALUES(?,?)";
$stmt = $mysqli -> prepare($sql);
$name = '王二';
$money = 150;
$stmt ->bind_param('si',$name,$money);
$result = $stmt -> execute();
var_dump($result);

<?php
$sql = '????'; //暂时不用赋值,用?代替
$mysqli -> prepare($sql); //创建预编译对象
$stmt -> bind_param(); //参数赋值 string-s int-i double-d bool-b
$stmt -> bind_result(); //绑定结果集
$stmt -> execute(); //执行代码
$stmt -> fetch(); //取出结果集

实例

header("content-type:text/html;charset=utf-8");
$mysqli = new mysqli('127.0.0.1','root','root','mysqli');
$mysqli -> query('set names utf8' );
$sql = "SELECT * FROM users WHERE id>?";
$stmt = $mysqli -> prepare($sql);
$id = 1;
$stmt -> bind_param('i',$id);
$stmt -> bind_result($id,$name,$money);
$stmt -> execute();
while($stmt -> fetch()){
    echo $name.'<br/>';
}