<?php $db = new PDO('mysql:host=localhost;dbname=db', 'Account', 'Password', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8';")); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); try{ //Execute a prepared statement with an array of insert values (named parameters) $sql = "INSERT INTO php(number,age) VALUES(:m_number, :m_age)"; $exe = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); $exe->execute(array(':m_number' => 10, ':m_age' => 20)); $exe = null; //Execute a prepared statement with bound variables $sql = "INSERT INTO php(number,age) VALUES(:m_number, :m_age)"; $exe = $db->prepare($sql); $m_number = 30; $m_age = 40; $exe->bindParam(':m_number', $m_number, PDO::PARAM_INT); $exe->bindParam(':m_age', $m_age, PDO::PARAM_INT); $exe->execute(); $exe = null; //Execute a prepared statement with an array of insert values (placeholders) $sql = "INSERT INTO php(number,age) VALUES(?, ?)"; $exe = $db->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)); $exe->execute(array(50, 60)); $exe = null; //Execute a prepared statement with question mark placeholders $sql = "INSERT INTO php(number,age) VALUES(?, ?)"; $exe = $db->prepare($sql); $m_number = 70; $m_age = 80; $exe->bindParam(1, $m_number, PDO::PARAM_INT); $exe->bindParam(2, $m_age, PDO::PARAM_INT); $exe->execute(); $exe = null; $sql = null; $m_age = null; $m_number = null; }catch(PDOException $ex){ echo $ex; } $db = null; ?>
執行前:
執行後:
參考資料:
http://www.php.net/manual/en/pdo.prepare.php
http://www.php.net/manual/en/pdostatement.execute.php