Home > Database > Mysql Tutorial > mysql预编译处理(mysqli、PDO)_MySQL

mysql预编译处理(mysqli、PDO)_MySQL

WBOY
Release: 2016-06-01 13:00:01
Original
1218 people have browsed it

DML语句预编译:

MysqLi:

<?php

	$mysqli = new mysqli("localhost","root","root","dbname");
	$mysqli->query("set names utf8");
	$sql = &#39;insert into user(id,name,age,email) values (?,?,?,?)&#39;;
	$mysqli_stmt = $mysqli->prepare($sql);


	$id = 2;
	$name = &#39;kung&#39;;
	$age = 28;
	$email = &#39;ohdas@163.com&#39;;
	
	$mysqli_stmt->bind_param(&#39;isis&#39;,$id,$name,$age,$email);

	$res = $mysqli_stmt->execute();

	if(!$res){
		echo &#39;error&#39;.$mysqli_stmt->error;
		exit;
	}else{
		echo &#39;ok&#39;;
	}

	$id = 3;
	$name = &#39;xiaoyu&#39;;
	$age = 28;
	$email = &#39;kung-yu@163.com&#39;;

	$mysqli_stmt->bind_param(&#39;isis&#39;,$id,$name,$age,$email);
	$res = $mysqli_stmt->execute();

	if(!$res){
		echo &#39;error&#39;.mysqli_stmt->error;
		exit;
	}else{
		echo &#39;ok&#39;;
	}
?>
Copy after login

PDO:

<?php
	$dns = &#39;mysql:dbname=dbname;host=127.0.0.1&#39;;
	$user = &#39;root&#39;;
	$password = &#39;root&#39;;
try{	
	$pdo = new PDO($dns,$user,$password);
} catch(PDOException $e){
	echo $e->getMessage();
}
	$pdo->query("set names utf8");
	
	$sql = &#39;inser into user values(:id,:name,:age,:email)&#39;;
	$pdo_stmt = $pdo->prepare($sql);
	
	$id = 2;
	$name = &#39;kung&#39;;
	$age = 27;
	$email = &#39;ohdas@163.com&#39;;

	$pdo_stmt->bindParam(&#39;:id&#39;,$id);
	$pdo_stmt->bindParam(&#39;:name&#39;,$name);
	$pdo_stmt->bindParam(&#39;:age&#39;,$age);
	$pdo_stmt->bindParam(&#39;:email&#39;,$email);
	$pdo_stmt->execute();
?>
Copy after login

DQL语句预编译:

mysqli:

<?php
	$mysqli = new mysqli("localhost","root","root","dbname");
	$mysqli->query("set names utf8");
	$sql = " select id,name from user where id > ?";
	$mysqli_stmt = $mysqli->prepare($sql);
	
	$id = 1;
	$mysqli_stmt->bind_param(&#39;i&#39;,$id);
	$mysqli_stmt->bind_result($id,$name);
	$mysqli_stmt->execute();
	
	while($mysqli_stmt->fetch()){
		echo $id.&#39;--&#39;.$name;
	}

	$mysqli_stmt->close();
	$mysqli->close();
?>
Copy after login


source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template