Correction status:Uncorrected
Teacher's comments:
<?php header('content-type:text/html;charset=utf-8'); $dsn = 'mysql:host=127.0.0.1;dbname=teststudy;charset=utf8;port=3306'; $dsn = 'mysql:dbname=teststudy'; $dbname = 'root'; $dbpw = 'root'; // try catch 捕捉到执行期的任何错误 // getMessage 方法获取错误消息 try{ $pdo = new PDO($dsn,$dbname,$dbpw); } catch (PDOException $e) { print_r($e->getMessage()); } //PDO对象实现查询记录 $sql1="select * from usertable where `sex`=?"; $stmt=$pdo->prepare($sql1); $sex="女"; $stmt->bindParam(1,$sex); $stmt->execute(); $data = $stmt->fetchAll(PDO::FETCH_ASSOC); print_r($data); //pdo对象实现增加一条记录 $sql2="insert into usertable(name,age,sex,birth,unit,email,phone)values(?,?,?,?,?,?,?)"; $stmt=$pdo->prepare($sql2); //预处理 $stmt->bindParam(1,$name); //绑定参数 $stmt->bindParam(2,$age); $stmt->bindParam(3,$sex); $stmt->bindParam(4,$birth); $stmt->bindParam(5,$unit); $stmt->bindParam(6,$email); $stmt->bindParam(7,$phone); $name ="we"; $age = 15; $sex ="女"; $birth = "19900101"; $unit = "home"; $email = "we@mail.com"; $phone = "17700220202"; $flag = $stmt->execute(); //返回值是sql语句是否正确,只要sql语句正确,那么返回值都是true //PDO对象实现删除一条记录 $sql3="DELETE FROM usertable WHERE id=7"; $res=$pdo->exec($sql3); if($res){ echo "success"; } $sql4="UPDATE usertable set name='nana' WHERE id=1"; $res=$pdo->exec($sql4); if($res){ echo "success"; }
点击 "运行实例" 按钮查看在线实例