mysqli扩展库的 预处理技术 mysqli stmt

时间:2023-03-09 05:59:26
mysqli扩展库的 预处理技术  mysqli stmt

问题的提出?

现在需要向mysql数据库添加100个用户,请问如何实现?

思路:

  1. 使用for循环100次,向数据库中添加100个用户.
  2. 使用批量添加

    $sql1=”insert xxx”;

    $ssql.=”insert xxx ”;

    。。。

使用$msyqli->mutil_query($sql1);

  3.方案使用预编译技术,该方案还可以防止sql注入攻击.

<?php

    //预编译演示
//需求: 请使用预处理的方式,向数据库添加三个用户
//1.创建mysqli对象
$mysqli=new MySQLi("localhost","root","hsp123","test"); //2.创建预编译对象
$sql="insert into user1 (name,password,email,age) values(?,?,?,?)";
$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);//prepare($sql)预处理函数
//绑定参数
$name="小倩";
$password="xiaoqian";
$email="aa@sohu.com";
$age="";
//参数绑定->给?赋值,这里类型和顺序都要对应.
//
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age);
//执行
$b=$mysqli_stmt->execute(); //继续添加
$name="老妖";
$password="laoyao";
$email="laoyao@sohu.com";
$age=""; $mysqli_stmt->bind_param("sssi",$name,$password,$email,$age); //执行
$b=$mysqli_stmt->execute() ; //继续添加
$name="菜层";
$password="aaa";
$email="aa@sohu.com";
$age="";
$mysqli_stmt->bind_param("sssi",$name,$password,$email,$age); //执行
$b=$mysqli_stmt->execute(); if(!$b){
die("操作失败".$mysqli_stmt->error);
}else{
echo "操作ok";
}
//释放
$mysqli->close(); ?>

现在我们看看mysqli的一些其他常用函数

案例: 编写一函数,接收一个表名,然后把表头和表数据,显示页面

<?php
function showTable($table_name){
$mysqli=new MySQLi("localhost","root","hsp123","test");
if(mysqli_connect_error()){
die(mysqli_connect_error());
}
//$sql="select * from $table_name";
$sql="desc user1";
$res=$mysqli->query($sql);
//如何获取返回总行数和列数
echo "共有 行".$res->num_rows." -列=".$res->field_count;
echo "<table border='1'><tr>";
//如何取出表头,从$res取出
while($field=$res->fetch_field()){
echo "<th>{$field->name}</th>";
}
echo "</tr>";
//循环取出数据
while($row=$res->fetch_row()){
echo "<tr>";
foreach($row as $val){
echo "<td>$val</td>";
}
echo "</tr>";
}
echo "</table>";
//关闭资源
$res->free();
$mysqli->close();
} showTable("user1");
?>