[PHP] 纯文本查看 复制代码 <?php
// 设置错误异常捕捉
// $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
try{
$dsn = "mysql:host=localhost;dbname=bookstore";
$pdo = new PDO($dsn, "root", "****");
}catch(PDOException $e){
echo "数据库连接失败:".$e->getMessage();
exit;
}
try{
// 准备好语句,数据库预编译
$sql = "insert into books(bookname, publisher, author, price) values(?, ?, ?, ?)";
$stream = $pdo->prepare($sql);
// 绑定参数
$stream->bindParam(1, $bookname);
$stream->bindParam(2, $publisher);
$stream->bindParam(3, $author);
$stream->bindParam(4, $price);
// 给变量赋值
$bookname = "book".rand(10, 99);
$publisher = "Publisher".rand(100, 999);
$author = "Author".rand(10, 99);
$price = rand(50, 150);
// 执行语句
$stream->execute();
}catch(PDOException $e){
echo $e->getMessage();
}
|