mysqli预处理实现增删改查

<?php
//预处理实现添加(删改同类)
$mysqli=new mysqli('localhost','root','root','test');
$mysqli->query("set names utf8");
//创建预编译对象
$sql="insert into user1(name,password,email,age) values (?,?,?,?)";
$mysqli_stmt=$mysqli->prepare($sql);
//绑定参数(给?赋值)
$name="小k" ;
$password="1234";
$email="[email protected]";
$age="54";
//'s'为字符串类型,‘i'为整型int,’d'为double型,类型和顺序一定要一一对应
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//执行
$b=$mysqli_stmt->execute();

$name="小天" ;
$password="179894";
$email="[email protected]";
$age="12";
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//执行
$b=$mysqli_stmt->execute();


if(!$b) {
    die("添加失败".$mysqli_stmt->error);
}
else {
    echo "成功";
}
$mysqli_stmt->close();
?>

<?php

//预处理实现查询

$mysqli=new mysqli('localhost','root','root','test');
$mysqli->query("set names utf8");

$sql="select id,name,email from user1 where id>?";
$mysqli_stmt=$mysqli->prepare($sql);
//绑定参数
$id=5;
$mysqli_stmt->bind_param("i",$id);

//绑定结果集
$mysqli_stmt->bind_result($id,$name,$email);
//执行
$mysqli_stmt->execute();
//取出绑定的值
while($mysqli_stmt->fetch())
{
    echo "$id--$name--$email";
    echo "<br>";
}

//绑定参数
$id=10;
$mysqli_stmt->bind_param("i",$id);

//绑定结果集 //只需绑定一次
//$mysqli_stmt->bind_result($id,$name,$email);
//执行
$mysqli_stmt->execute();
//取出绑定的值
while($mysqli_stmt->fetch())
{
    echo "$id--$name--$email";
    echo "<br>";
}


$mysqli_stmt->free_result();
$mysqli_stmt->close();
$mysqli->close();

?>

猜你喜欢

转载自blog.csdn.net/zch3210/article/details/77099924