<?php header('Content-Type:text/html;charset=UTF-8'); try { //连接数据库 $dsn = 'mysql:host=localhost;dbname=demo'; $userName = 'root'; $password = 'root'; $pdo = new PDO($dsn,$userName,$password); //创建预处理sql语句 $sql = "INSERT `user` SET `name`=:name,`email`=:email,`password`=sha1(:password),`birthday`=:birthday"; //执行预处理sql语句,创建一个预处理对象PDOStatement $pdoStmt = $pdo->prepare($sql); //var_dump($pdoStmt); //判断预处理对象是否创建成功 if ($pdoStmt == true) { //新建插入数据 $data = ['name'=>'插入','email'=>'cr@qq.com','password'=>'321','birthday'=>'1998-02-29']; //执行预处理语句 $res = $pdoStmt->execute($data); //var_dump($res); if ($res == true) { echo '新增成功!'.$pdo->lastInsertId().''; } else { echo '新增失败'.$pdo->errorInfo().''; } } else { print_r($pdo->errorInfo()); //创建失败返回错误语句 } } catch (PDOException $e) { echo $e->getMessage(); exit();//终止当前脚本 }