PHP 中可以使用 PDO 访问数据,PHP 5.0 后自带 PDO,PDO 还能防止 SQL 注入功能。
DBUtils.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| <?php class DBUtils { public static function query($sql, $params) { $results = array();
try { $db = new PDO("mysql:host=localhost;dbname=test", "root", "root", array(PDO::ATTR_PERSISTENT => true));
$preparedStatement = $db->prepare($sql); $preparedStatement->execute($params);
foreach ($preparedStatement as $row) { array_push($results, $row); }
$db = null; } catch (PDOException $e) { print "Error: " . $e->getMessage() . "<br/>"; die(); }
return $results; } } ?>
|
a.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?php
ini_set("display_errors", "On"); error_reporting(E_ALL | E_STRICT);
include_once "DBUtils.php";
$sql = "SELECT * FROM foo WHERE name=:name OR city=:city";
$results = DBUtils::query($sql, array(":name"=>"Biao", ":city"=>"Beijin")); var_dump($results); ?>
|
测试