首页 > 代码库 > MySqli 中预处理类 stmt

MySqli 中预处理类 stmt

非select 语句(没有结果集的)

1.建立连接数据库

  $mysqli=new mysqli("localhost","root","","sqldb");

2.判断

  if(mysqli_connect_error()){

    echo "连接数据库失败".mysqli_connect_error();

      exit;

  }

3.SQL语句拼装

  $sql="insert into shops(name,price,description) values(?,?,?,?)";

  $sql="update shops set name=?,price=?,num=?,description=?; where id=?";

4.插入SQL 语句

  $stmt=$mysqli->prepare($sql);//比较方便

5.给每一个符号的?传值(绑定参数)

  $stmt->bind_param("sdisi",$name,$price,$num,$description,$id);

6.传值

  $name="zhangsan";

  $price=22.22;

  $num=10;

  $description="very good";

  $id=10;

7.执行

  $stmt->execute();

影响行数:$stmt->insert_id;

最后插入的ID:$stmt->offected_rows;

    $mysqli=@new mysqli("localhost","root","","sqldb");    if(mysqli_connect_error()){        echo "连接数据库错误".$mysqli_connect_error();    }    /*拼装数据*/    $sql="insert into shop values (null,?,?,?)";    $sql="update shop set name=?,price=?,description=? where id=?";    /*插入数据*/    $stmt=$mysqli->prepare($sql);    /*绑定数据*/    $stmt->bind_param("sdsi", $name, $price, $description, $id);    /*赋值*/    $name="zhangsanasdfadfasdfasdf";    $price=2.3;    $description="very good";    $id=1;    /*执行*/    $stmt->execute();

 

select 语句(有结果集的)

 

1.连接数据库

  $mysqli=new mysqli("localhost","root","","sqldb");

2.判断数据库

  if(mysqli_connect_error()){

    echo "Error:".mysqli_connect_error();

  }

3.拼接数据库

  $sql="select id,name,price,description where id=?";

4.插入数据库

  $stmt=$myqli->prepare($sql);

5.绑定数据库

  $stmt->bind_param(i,$id);

6.绑定结果集

  $stmt->bind_result($id,$name,$price,$description);

7.赋值

  $id=10;

8.执行

  $stmt->execute();

9.取出结果集

  $stmt->store_result();

10.while 查看结果

  while($stmt->fetch()){

    echo "$id---$name---$price--$description";

  }

11.关闭结果集

  $stmt->free_result();

12.关闭数据库

  $stmt->close();

<?php    $mysqli= @new MySQLi("localhost","root","","sqldb");    if(mysqli_connect_error()){        echo "Error:".mysqli_connect_error();    }    /*拼装SQL*/    $sql="select id,name,price,description from shop where id<?";    /*插入*/    $stmt=$mysqli->prepare($sql);    var_dump($stmt);    /*绑定*/    $stmt->bind_param(i,$id);    /*绑定结果集*/    $stmt->bind_result($id,$name,$price,$description);    /*赋值*/    $id=10;    /*执行*/    $stmt->execute();    /*取出结果集*/    $stmt->store_result();    echo "<table border=‘1‘>";    //字段信息、列信息    $result=$stmt->result_metadata();        echo "<tr>";    while($field=$result->fetch_field()){        echo "<th>{$field->name}</th>";    }        echo "</tr>";        /*fetch()查看结果集*/    /*移动数据库指针*/    //$stmt->data_seek(2);    while($stmt->fetch()){        echo "<tr>";        echo "<td>$id</td><td>$name</td><td>$price</td><td>$description</td>";        echo "</tr>";    }    echo "</table>";    /*关闭结果集*/    $stmt->free_result();    /*关闭数据库d*/    $stmt->close();?>