php教程

超轻量级php框架startmvc

PHP使用PDO创建MySQL数据库、表及插入多条数据操作示例

更新时间:2020-04-05 14:13:24 作者:startmvc
本文实例讲述了PHP使用PDO创建MySQL数据库、表及插入多条数据操作。分享给大家供大家参考

本文实例讲述了PHP使用PDO创建MySQL数据库、表及插入多条数据操作。分享给大家供大家参考,具体如下:

创建 MySQL 数据库:


<?php
$servername = "localhost";
$username = "username";
$password = "password";
try {
 $conn = new PDO("mysql:host=$servername", $username, $password);
 // 设置 PDO 错误模式为异常
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 $sql = "CREATE DATABASE myDBPDO";
 // 使用 exec() ,因为没有结果返回
 $conn->exec($sql);
 echo "数据库创建成功<br>";
}
catch(PDOException $e)
{
 echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

创建 MySQL 表:


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
 $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
 // 设置 PDO 错误模式,用于抛出异常
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 // 使用 sql 创建数据表
 $sql = "CREATE TABLE MyGuests (
 id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
 firstname VARCHAR(30) NOT NULL,
 lastname VARCHAR(30) NOT NULL,
 email VARCHAR(50),
 reg_date TIMESTAMP
 )";
 // 使用 exec() ,没有结果返回
 $conn->exec($sql);
 echo "数据表 MyGuests 创建成功";
}
catch(PDOException $e)
{
 echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

向 MySQL 插入多条数据:


<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";
try {
 $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
 // set the PDO error mode to exception
 $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
 // 开始事务
 $conn->beginTransaction();
 // SQL 语句
 $conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
 VALUES ('John', 'Doe', 'john@example.com')");
 $conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
 VALUES ('Mary', 'Moe', 'mary@example.com')");
 $conn->exec("INSERT INTO MyGuests (firstname, lastname, email)
 VALUES ('Julie', 'Dooley', 'julie@example.com')");
 // 提交事务
 $conn->commit();
 echo "新记录插入成功";
}
catch(PDOException $e)
{
 // 如果执行失败回滚
 $conn->rollback();
 echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>

PHP PDO 创建 MySQL数据库 插入多条数据