实例1.PDO新增数据
<?php // 新增数据 //1.连接数据库 try { $dsn = 'mysql:host=127.0.0.1;dbname=myphp'; $pdo = new PDO($dsn, 'root', 'root'); } catch (PDOException $e) { die('数据库连接失败' . $e->getMessage()); } echo '数据库连接成功'; //2.执行操作 $sql = 'INSERT INTO `staff` (`name`, `age`, `sex`, `position`, `mobile`, `hiredate`)'; $sql .= 'VALUES (:name, :age, :sex, :position, :mobile, :hiedate)'; $stmt = $pdo->prepare($sql); $name = '于禁'; $age = 32; $sex = 1; $position = '护卫长'; $mobile = '1335411789'; $hiedate = time(); //变量与占位符相绑定 $stmt->bindParam(':name', $name, PDO::PARAM_STR); $stmt->bindParam(':age', $age, PDO::PARAM_INT); $stmt->bindParam(':sex', $sex, PDO::PARAM_INT); $stmt->bindParam(':position', $position, PDO::PARAM_STR); $stmt->bindParam(':mobile', $mobile, PDO::PARAM_STR); $stmt->bindParam(':hiedate', $hiedate, PDO::PARAM_INT); //执行SQL语句 $stmt->execute(); //$stmt->rowCount(),返回当前数据表中受影响的条数 if ($stmt->rowCount() > 0) { echo '成功添加了' . $stmt->rowCount() . '条数据'; } //3.关闭连接 $pdo = null; $sql = null;
运行实例 »
实例2.PDO更新数据
<?php // 更新数据 //1.连接数据库 try { $dsn = 'mysql:host=127.0.0.1;dbname=myphp'; $pdo = new PDO($dsn, 'root', 'root'); } catch (PDOException $e) { die('数据库连接失败' . $e->getMessage()); } echo '数据库连接成功'; echo '<br>'; //2.执行操作 $sql = "UPDATE `staff` SET `position` = :position WHERE `id` = :id"; $stmt = $pdo->prepare($sql); //执行SQL语句 $stmt->execute(['position' => '东吴主公', 'id' => 12]); //$stmt->rowCount(),返回当前数据表中受影响的条数 if ($stmt->rowCount() > 0) { echo '成功更新了' . $stmt->rowCount() . '条数据'; } //3.关闭连接 $pdo = null; $sql = null;
运行实例 »
实例3.PDO删除数据
<?php // 删除数据 //1.连接数据库 try { $dsn = 'mysql:host=127.0.0.1;dbname=myphp'; $pdo = new PDO($dsn, 'root', 'root'); } catch (PDOException $e) { die('数据库连接失败' . $e->getMessage()); } echo '数据库连接成功'; echo '<br>'; //2.执行操作 $sql = 'DELETE FROM `staff` WHERE `id`=:id'; $stmt = $pdo->prepare($sql); //执行SQL语句 $stmt->execute(['id' => 8]); //$stmt->rowCount(),返回当前数据表中受影响的条数 if ($stmt->rowCount() > 0) { echo '成功删除了' . $stmt->rowCount() . '条数据'; } //3.关闭连接 $pdo = null; $sql = null;
运行实例 »
点击 "运行实例" 按钮查看在线实例