本文实例讲述了php实现基于PDO的预处理。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
$servername = "localhost" ;
$username = "root" ;
$password = "admin" ;
//$dbname为我的test数据库
$dbname = "test" ;
try {
$conn = new PDO( "mysql:host=$servername;dbname=$dbname" , $username , $password );
//设置pdo错误异常处理
$conn ->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
//预处理SQL并绑定参数
$stmt = $conn ->prepare( "INSERT INTO user(user_first,user_last,age)VALUES(:user_first,:user_last,:age)" );
$stmt ->bindParam( ":user_first" , $user_first );
$stmt ->bindParam( ":user_last" , $user_last );
$stmt ->bindParam( ":age" , $age );
//要执行的插入记录
$user_first = "xiao" ;
$user_last = "liang" ;
$age =15;
$stmt ->execute();
//要执行的插入记录
$user_first = "xiao" ;
$user_last = "cheng" ;
$age =23;
$stmt ->execute();
echo "News record created successfully!" ;
} catch (PDOException $e ){
echo "Error:" . $e ->getMessage();
}
$conn =null;
|
希望本文所述对大家PHP程序设计有所帮助。