<?php //连接数据库 $pdo=new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); //print_r($pdo); //创建预处理对象 $sql ='INSERT INTO `staff`(`name`,`age`,`sex`,`position`,`mobile`,`hiredate`)'; $sql .='VALUES (:name,:age,:sex,:position,:mobile,:hiredate)'; $stmt=$pdo->prepare($sql); ////绑定 //$name='李萌'; //$age='25'; //$sex='1'; //$position='吃瓜群众'; //$mobile='15299999999'; //$hiredate=time(); // ////parameter:参数,variable:变量,data type:类型,length:长度 //$stmt->bindParam(':name',$name,PDO::PARAM_STR,20); //$stmt->bindParam(':age',$age,PDO::PARAM_INT,3); //$stmt->bindParam(':sex',$sex,PDO::PARAM_INT,1); //$stmt->bindParam(':position',$position,PDO::PARAM_STR,20); //$stmt->bindParam(':mobile',$mobile,PDO::PARAM_INT,11); //$stmt->bindParam(':hiredate',$hiredate,PDO::PARAM_INT,10); // //$stmt->execute(); //使用数组的方式添加 $key=['name','age','sex','position','mobile','hiredate']; $demo=['李大大',25,1,'路人甲','15648421111',time()]; //使用array_combine()函数来是两个数组绑定 $data=array_combine($key,$demo); //查看下数组 //echo '<pre>'.print_r($data,true);die(); //将$data当成值传给execute()函数 $stmt->execute($data); //检测是否成功 if($stmt->rowCount()>0){ echo '成功的添加了'.$stmt->rowCount().'条记录'; } //关闭连接 $pdo=null;
点击 "运行实例" 按钮查看在线实例