Blogger Information
Blog 15
fans 0
comment 0
visits 10352
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
PDO新增数据方法2019.2.25
ken的博客
Original
1096 people have browsed it

实例

<?php
//新增数据
//1.连接数据库

$pdo = new PDO('mysql:host=127.0.0.1;dbname=php;','root','root');

//2.创建预处理对象
$sql='INSERT INTO `staff`(`name`,`age`,`sex`,`position`,`mobile`,`hiredate`)';
$sql.='VALUES(:name,:age,:sex,:position,:mobile,:hiredate)';  //语句模板
$stmt = $pdo->prepare($sql);//向预处理语句传递值


//3.执行操作
//参数绑定
//$name='郑成功';
//$age=50;
//$sex=1;
//$position='突击队员';
//$mobile='13821579856';
//$hiredate=time();

//方法一:绑定一个参数到指定的变量名
//$stmt->bindParam('name',$name,PDO::PARAM_STR,30);
//$stmt->bindParam('age',$age,PDO::PARAM_INT,3);
//$stmt->bindParam('sex',$sex,PDO::PARAM_INT,1);
//$stmt->bindParam('position',$position,PDO::PARAM_STR,40);
//$stmt->bindParam('mobile',$mobile,PDO::PARAM_STR,11);
//$stmt->bindParam('hiredate',$hiredate,PDO::PARAM_INT,10);
//方法二: 把一个值绑定到一个参数
$stmt->bindValue('name','李时珍',PDO::PARAM_STR);
$stmt->bindValue('age',60,PDO::PARAM_INT);
$stmt->bindValue('sex',1,PDO::PARAM_INT);
$stmt->bindValue('position','医生',PDO::PARAM_STR);
$stmt->bindValue('mobile','13999999999',PDO::PARAM_STR);
$stmt->bindValue('hiredate',time(),PDO::PARAM_INT);
//方法三:创建2个数组一个值一个键,合成二维数组然后传参输出
//$key=['name','age','sex','position','mobile','hiredate'];
//$value=['许昆贤',30,1,'PHP程序员','18321281156',time()];
//$date = array_combine($key,$value);
$stmt->execute();
if($stmt->rowCount()>0){
    echo '成功添加'.$stmt->rowCount().'条记录';
}

//4.关闭数据库连接
$pdo = null;

运行实例 »

点击 "运行实例" 按钮查看在线实例

Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post