这是关于如何使用 PHP 的 PDO 对象将行插入 MySQL 数据库的初学者教程。请注意,我还写了一篇关于如何使用 PDO 进行多插入的教程。但是,对于本教程,我将坚持基础知识。
示例 MySQL 表:
- CREATE TABLE IF NOT EXISTS `cars` (
- `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
- `make` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
- `model` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
出于本示例的目的,我创建了一个名为cars的简单表。如果您打算使用 PDO 扩展,请务必将上述 SQL 导入您自己的数据库。
首先,我们需要使用 PDO 对象连接到 MySQL。
- //MySQL connection details.
- $host = 'localhost';
- $user = 'root';
- $pass = '';
- $database = 'test';
-
- //Custom PDO options.
- $options = array(
- PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
- PDO::ATTR_EMULATE_PREPARES => false
- );
-
- //Connect to MySQL and instantiate our PDO object.
- $pdo = new PDO("mysql:host=$host;dbname=$database", $user, $pass, $options);
一旦我们连接到 MySQL 并选择了我们的数据库,我们就可以执行一个准备好的插入语句:
- //Create our INSERT SQL query.
- $sql = "INSERT INTO `cars` (`make`, `model`) VALUES (:make, :model)";
-
-
- //Prepare our statement.
- $statement = $pdo->prepare($sql);
-
-
- //Bind our values to our parameters (we called them :make and :model).
- $statement->bindValue(':make', 'Nissan');
- $statement->bindValue(':model', 'Primera');
-
-
- //Execute the statement and insert our values.
- $inserted = $statement->execute();
-
-
- //Because PDOStatement::execute returns a TRUE or FALSE value,
- //we can easily check to see if our insert was successful.
- if($inserted){
- echo 'Row inserted!
'; - }
使用 PDO 对象向 MySQL 中插入一行的过程实际上非常简单:
请注意,您可以重复使用相同的语句来插入多行:
- //Create our SQL query.
- $sql = "INSERT INTO `cars` (`make`, `model`) VALUES (:make, :model)";
-
-
- //Prepare our statement using the SQL query.
- $statement = $pdo->prepare($sql);
-
-
- //Bind our values to our parameters (we called them :make and :model).
- $statement->bindValue(':make', 'Nissan');
- $statement->bindValue(':model', 'Primera');
-
-
- //Execute the statement and insert our values.
- $inserted = $statement->execute();
-
- //Because PDOStatement::execute returns a TRUE or FALSE value,
- //we can easily check to see if our insert was successful.
- if($inserted){
- echo 'Row inserted!
'; - }
-
- //For our next row, we're going to insert a Honda Civic.
- //We will re-use the statement that we already prepared.
- $statement->bindValue(':make', 'Honda');
- $statement->bindValue(':model', 'Civic');
-
-
- //Execute the statement and insert our values.
- $statement->execute();
请注意我们如何两次执行相同的语句,而不必为每次插入准备一个新语句。
还有一个速记版本。
- //Create our SQL query.
- $sql = "INSERT INTO `cars` (`make`, `model`) VALUES (?, ?)";
-
- //Prepare the statement.
- $statement = $pdo->prepare($sql);
-
- //Execute it
- $statement->execute(array('Honda', 'Civic'));
如您所见,这种方法要快得多。
PDO初学者的相关阅读: