>  기사  >  데이터 베이스  >  mysql预编译处理(mysqli、PDO)_MySQL

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

WBOY
WBOY원래의
2016-06-01 13:00:011150검색

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


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.