如何用PDO 取代MySQL 函式
簡介:
My連接到MySQL 和MSSQL 資料庫:
MySQL:
$dsn = 'mysql:dbname=database_name;host=localhost'; $user = 'username'; $password = 'password'; $dbh = new PDO($dsn, $user, $password);
$dsn = 'sqlsrv:Server=localhost;Database=database_name'; $user = 'username'; $password = 'password'; $dbh = new PDO($dsn, $user, $password);
執行查詢:
PDO 使用準備好的語句執行查詢,防止SQL 注入。
$SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username';
範例SQL:
// Prepare statement with array of named variables $result = $dbh->prepare($SQL); $result->execute([':username' => $username]); // OR // Prepare statement with named placeholder indicator $result = $dbh->prepare($SQL); $result->bindValue(':username', $username); $result->execute();
執行查詢:
// Fetch a single row as an array $row = $result->fetch(); // Fetch all rows as an array $rows = $result->fetchAll();
取得結果:
使用輔助類:
class PDOConnection { public $connection; public function __construct($dsn, $username, $password) { $this->connection = new PDO($dsn, $username, $password); $this->connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } public function query($SQL) { return $this->connection->query($SQL); } public function prepare($SQL, $params = []) { $result = $this->connection->prepare($SQL); $result->execute($params); return $result; } }
要簡化資料庫交互,請考慮使用如下所示的類:
$db = new PDOConnection($dsn, $user, $password); $SQL = 'SELECT ID, EMAIL FROM users WHERE user = :username'; $result = $db->prepare($SQL, ['username' => $username]); while ($row = $result->fetch()) { echo $row['ID'] . ' ' . $row['EMAIL']; }
以上是如何用 PDO 取代 MySQL 函數:PHP 中的現代資料庫連線指南?的詳細內容。更多資訊請關注PHP中文網其他相關文章!