首页 > 数据库 > mysql教程 > mysql预编译处理(mysqli、PDO)_MySQL

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

WBOY
发布: 2016-06-01 13:00:01
原创
1194 人浏览过

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();
?>
登录后复制


来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板