Heim  >  Artikel  >  Datenbank  >  mysql预编译处理(mysqli、PDO)_MySQL

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

WBOY
WBOYOriginal
2016-06-01 13:00:011150Durchsuche

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;;
	}
?>

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();
?>

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();
?>


Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn