1、连接数据库
return[ 'type' => 'mysql', 'host' => '127.0.0.1', 'port' => '3306', 'dbname' => 'student', 'username' => 'root', 'passwd' => 'root' ];
$db = require 'database.php'; $dns = "{$db['type']}:host={$db['host']};port={$db['port']};dbname={$db['dbname']}"; try { $pdo = new PDO($dns, $db['username'], $db['passwd']); } catch (PDOException $e) { die("Error!: " . $e->getMessage() . "<br/>"); }
require 'inc/connect.php';
2、 创建sql语句模板
$sql = 'INSERT INTO `user` SET `name` = :name, `abbreviations` = :abbreviations';
3、 创建sql语句对象(预处理对象)
$stmt = $pdo->prepare($sql);
4、 将变量绑定给sql语句模板上
$name = '赵六'; $abbreviations = 'zl'; $stmt->bindParam('name', $name, PDO::PARAM_STR); $stmt->bindParam('abbreviations', $abbreviations, PDO::PARAM_STR);
5、执行SQL语句
if ($stmt->execute()) { if ($stmt->rowCount() > 0) { //返回受影响的记录数 echo '成功添加了' . $stmt->rowCount() . '记录,主键是:' . $pdo->lastInsertId(); } else { die('<pre>' . print_r($stmt->errorInfo(), true)); } }
6、关闭数据库
$pdo = null;
二、修改
<?php //1、连接数据库 require 'inc/connect.php'; //2、 创建sql语句模板 $sql = 'UPDATE `user` SET `name` = :name, `abbreviations` = :abbreviations WHERE `id` = :id'; //3.pdo预处理 $stmt = $pdo->prepare($sql); //4.将变量绑定给sql语句模板上 $name = '张伟'; $abbreviations='zw'; $id = 2; $stmt->bindParam('name', $name, PDO::PARAM_STR); $stmt->bindParam('abbreviations', $abbreviations, PDO::PARAM_STR); $stmt->bindParam('id', $id, PDO::PARAM_INT); //5、执行SQL语句 if ($stmt->execute()) { echo '成功执行'; } else { echo '执行失败'; } //6、关闭链接 $pdo = null;
三、删除
<?php //1、连接数据库 require 'inc/connect.php'; //2、 创建sql语句模板 $sql='DELETE FROM `user` WHERE `id` = :id'; //3.pdo预处理 $stmt = $pdo->prepare($sql); //4.将变量绑定给sql语句模板上 $id = 2; $stmt->bindParam('id', $id, PDO::PARAM_INT); //5、执行SQL语句 if ($stmt->execute()) { echo '成功执行'; } else { echo '执行失败'; } //6、关闭链接 $pdo = null;