批改状态:未批改
老师批语:
<?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;点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号