Correcting teacher:天蓬老师
Correction status:qualified
Teacher's comments:数据库的操作, 还是要多多练习
PDO链接数据库: <?php $db = [ 'type' => 'mysql', 'host' => 'localhost', 'dbname' => 'localhost', 'username' => 'wenbin0209', 'password' => 'a384309596', 'port' => 3306 ]; $dsn = "{$db['type']}:host={$db['host']};dbname={$db['dbname']}"; try { $pdo = new PDO($dsn,$db['username'],$db['password']); } catch(PDOException $e){ die('错误信息:'.$e->getMessage()); } // echo '请求成功'; PDO增删查改操作: <?php // 连接数据库 require('db.php'); // ------------增加数据-------------- // 创建语句模板 $sql = 'INSERT INTO `ls_addressbook` SET `province`=:province, `tel`=:tel '; //创建sql语句 $stmt = $pdo->prepare($sql); // 预处理语句中进行绑定数据 $province = '山东'; $tel = 13964328052; $stmt->bindParam('province',$province,PDO::PARAM_STR); $stmt->bindParam('tel',$tel,PDO::PARAM_INT); // print_r($stmt); // PDOStatement类 进行增删查改操作 $add = $stmt ->execute(); print_r($add); //--------- 删除数据------------ // 删除指定id的数据 $sql = 'DELETE from `ls_addressbook` where id = :id'; // 创建语句 $stmt = $pdo->prepare($sql); $id = 40; $stmt ->bindParam('id',$id); // 执行删除 $delete = $stmt ->execute(); //影响行数 print_r($stmt->rowCount()); //-----------查询数据---------- //查询全部数据 $sql = 'SELECT * from `ls_addressbook`'; $stmt = $pdo->prepare($sql); $select = $stmt->execute(); print_r($stmt->fetchAll()); // 更新数据 $sql = 'UPDATE `ls_addressbook` set name = :name where id = :id'; $stmt = $pdo->prepare($sql); // 绑定数据 $name = '老王'; $id = 42; $stmt ->bindParam('name',$name); $stmt ->bindParam('id',$id); $update = $stmt->execute(); print_r($update);
点击 "运行实例" 按钮查看在线实例