当前位置:首页 > PHP >

PHP PDO方式操作Sqlite实例

时间:2022-03-05 22:48:33浏览:668 转载

1、创建数据库

$pdo = new PDO('sqlite:php_sqlite_pdo.db');


会自动生成php_sqlite_pdo.db文件,文件名和后缀可根据需求修改


2、创建表


# Create table user
# (创建表)
$pdo->exec("CREATE TABLE IF NOT EXISTS user (
            id INTEGER PRIMARY KEY,
            name TEXT,
            time TEXT)");


创建一张user表,字段为id,name,time


3、插入数据

# Insert data
# (插入数据)
# 方式1
$sql = "INSERT INTO user (name, time) VALUES (:name, :time)";
$stmt = $pdo->prepare($sql);
$name = 'sunshine1';
$time = date('Y-m-d H:i:s');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':time', $time);
$stmt->execute();

# 方式2
$sql = "INSERT INTO user (name, time) VALUES (:name, :time)";
$stmt = $pdo->prepare($sql);
$stmt->bindValue(':name', 'sunshine2');
$stmt->bindValue(':time', date('Y-m-d H:i:s'));
$stmt->execute();

# 方式3
$sql = "INSERT INTO user (name, time) VALUES (:name, :time)";
$stmt = $pdo->prepare($sql);
$stmt->execute([':name' => 'sunshine3', ':time' => date('Y-m-d H:i:s')]);

# 方式4
$sql = "INSERT INTO user (name, time) VALUES (?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute(['sunshine4', date('Y-m-d H:i:s')]);

# 方式5
$sql = "INSERT INTO user (name, time) VALUES ('sunshine5', '" . date('Y-m-d H:i:s') . "')";
$pdo->exec($sql);

这里插入方式有多种,使用绑定方式PDO会自动处理SQL注入等安全问题


4、更新数据

# Update data
# (更新数据,参考插入多种方式)
$sql = "UPDATE user SET name = :name WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([':name' => 'sunshine1_updated', ':id' => 1]);

5、删除数据

# Delete data
# (删除数据)
$sql = "DELETE FROM user WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([':id' => 2]);

6、查询数据

# Select data
# (查询数据)
$sql = "SELECT * FROM user";
print_r($pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC));

7、清空数据

# Truncate data
# (清空数据)
$sql = "DELETE FROM sqlite_sequence WHERE name = 'user'";
$pdo->exec($sql);
$sql = "DELETE FROM user";
$pdo->exec($sql);




上一篇:Python中的os.listdir()方法及获取文件夹中所有文件的路径
下一篇:解决执行脚本报syntax error: unexpected end of file或syntax error near unexpected token fi错误的问题

发表评论

昵称:  验证码:

关于博主

博主

博主:BlueCode

职业:web程序

简介:2002年开始一直从事Web制作,网站运营,会PHP+MYSQL ASP+MSSQL,微信开发