PHP基础之预处理技术

demo1

//用预处理技术一次插入三个数据
	
	//1.连接数据库
	$mysqli=new mysqli('localhost','root','','test');
	
	if($mysqli->connect_error){
			die('连接失败'.$mysqli->connect_error);
	}
	$mysqli->query("set names utf8");
	
	//2.转换成预处理对象prepare()
	$sql="insert into user  (username,password,age) values (?,?,?)";
	
	$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);
	
	//3.绑定变量
	$username='李小龙';
	$password='123456';
	$age=33;
	
	$mysqli_stmt->bind_param('ssi',$username,$password,$age);
	
	//4.执行预处理语句
	$res = $mysqli_stmt->execute();
	
	
	//3.绑定变量
	$username='成龙';
	$password='123456';
	$age=60;
	
	$mysqli_stmt->bind_param('ssi',$username,$password,$age);
	
	//4.执行预处理语句
	$res = $mysqli_stmt->execute();
	
	if($res){
		echo '操作成功';	
	}else{
		echo $mysqli_stmt->error;
	}
	
	
	//5.关闭连接
	$mysqli_stmt->close();
	$mysqli->close();
	

demo2

//用预处理技术查询id>5的数据,并显示到网页
	
	//1.连接数据库
	$mysqli=new mysqli('localhost','root','','test');
	
	if($mysqli->connect_error){
			die('连接失败'.$mysqli->connect_error);
	}
	$mysqli->query("set names utf8");
	
	//2.转换成预处理对象
	$sql="select username,age from user where id>?";
	$mysqli_stmt=$mysqli->prepare($sql) or die($mysqli->error);

	//3.绑定变量和结果集
	$id=5;
	$mysqli_stmt->bind_param('i',$id);
	$mysqli_stmt->bind_result($username,$age);
	
	//4.执行预处理语句
	$mysqli_stmt->execute();
	while($row=$mysqli_stmt->fetch()){
		
		echo "<br />--$username--$age";
	}
	echo "<br />*******************************<br />";
	$id=8;
	
	$mysqli_stmt->bind_param('i',$id);
	$mysqli_stmt->bind_result($username,$age);
	
	//4.执行预处理语句
	$mysqli_stmt->execute();
	
	while($row=$mysqli_stmt->fetch()){
		
		echo "<br />--$username--$age";
	}
	
	//5.释放资源,关闭预编译,关闭连接
	$mysqli_stmt->free_result();
	$mysqli_stmt->close();
	
	$mysqli->close();

demo3

//传入一个表名,打印出表
	function showTab($tab){
		//1.连接数据库
		$mysqli=new mysqli('localhost','root','','test');
		if($mysqli->connect_error){
				die('连接失败'.$mysqli->connect_error);
		}
		$mysqli->query("set names utf8");
		//$sql="select * from $tab";
		$sql = "desc $tab";
		$res=$mysqli->query($sql);
		//得到列和行
		//$colum=$res->field_count;
		//$row=$res->num_rows;
		echo "<table border='1'>";
			//打印表头
			echo "<tr>";
			while($finfo=$res->fetch_field()){
				
				echo "<th>$finfo->name</th>";
				
			}
			echo "</tr>";
			//打印表内容
			while($row=$res->fetch_row()){
				
				echo "<tr>";
				foreach($row as $v){
					echo "<td>$v</td>";
				}
				echo "<tr>";
			}
			
		echo "</table>";
	}
	
	showTab('user');

猜你喜欢

转载自blog.csdn.net/weixin_42819066/article/details/85710277