我读了太多的问题和答案,但不确定。 我有2个问题
1。我将数据库连接转换为函数,但不确定是否 安全吗?
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'demo');
function DB()
{
try {
$pdo = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
} catch (PDOException $e) {
return "Error!: " . $e->getMessage();
die();
}
}
2。我的查询正确完成了吗?
查询:
try {
$pdo = DB();
$stmt = $pdo->prepare("SELECT * FROM settings");
$stmt->execute();
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$c = htmlspecialchars($row['site_url']);
$e = filterString($row['contact']);
}
unset($stmt);
} catch (PDOException $e) {
exit($e->getMessage());
}
感谢您的帮助
答案 0 :(得分:0)
也许保持一个连接,而不是打开与数据库的多个连接。您可以查看我创建的一个项目PDOEasy,以使MVC易于使用PDO或使用下面的静态示例。
class DB
{
private $_connection;
private static $_instance;
public static function getInstance() {
if(self::$_instance) return self::$_instance;
self::$_instance = new self();
return self::$_instance;
}
private function __construct() {
$this->_connection = new PDO('mysql:host='.DB_SERVER.';dbname='.DB_NAME.'', DB_USERNAME, DB_PASSWORD, array(
PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
));
}
public function getConnection() { return $this->_connection; }
}
可以像这样使用:
$stmt = DB::getInstance()
->getConnection()
->Prepare('SELECT * FROM settings');
$stmt->execute();
foreach($stmt->fetchAll() as $row) {
// ...
}