当前位置:Gxlcms > 数据库问题 > php mysqli扩展之预处理

php mysqli扩展之预处理

时间:2021-07-01 10:21:17 帮助过:2人阅读

define("HOST", "localhost"); define("USER", ‘root‘); define("PWD", ‘‘); define("DB", ‘test‘); $mysqli=new Mysqli(HOST,USER,PWD,DB); if ($mysqli->connect_errno) { "Connect Error:".$mysqli->connect_error; } $mysqli->set_charset(‘utf8‘); $id=‘‘; $title=‘title4‘; //用?代替 变量 $sql="INSERT test VALUES (?,?)"; //获得$mysqli_stmt对象,一定要记住传$sql,预处理是对sql语句的预处理。 $mysqli_stmt=$mysqli->prepare($sql); //第一个参数表明变量类型,有i(int),d(double),s(string),b(blob) $mysqli_stmt->bind_param(‘is‘,$id,$title); //执行预处理语句 if($mysqli_stmt->execute()){ echo $mysqli_stmt->insert_id; }else{ echo $mysqli_stmt->error; } $mysqli->close();

使用mysqli预处理防止sql注入:

$id=‘4‘;
$title=‘title4‘;

$sql="SELECT * FROM test WHERE id=? AND title=?";
$mysqli_stmt=$mysqli->prepare($sql);
$mysqli_stmt->bind_param(‘is‘,$id,$title);

if ($mysqli_stmt->execute()) {
    $mysqli_stmt->store_result();
    if($mysqli_stmt->num_rows()>0){
        echo "验证成功";
    }else{
        echo "验证失败";
    }
}
    $mysqli_stmt->free_result();
    $mysqli_stmt->close();

使用mysqli预处理执行查询语句:

$sql="SELECT id,title FROM test WHERE id>=?";

$mysqli_stmt=$mysqli->prepare($sql);
$id=1;

$mysqli_stmt->bind_param(‘i‘,$id);

if($mysqli_stmt->execute()){
    $mysqli_stmt->store_result();
//将一个变量绑定到一个prepared语句上用于结果存储
$mysqli_stmt->bind_result($id,$title); while ($mysqli_stmt->fetch()) { echo $id.‘ :‘.$title.‘<br/>‘; } }

    更多mysqli技术请参见php官方手册,查手册是学习的最好方法~

 

php mysqli扩展之预处理

标签:

人气教程排行