我正在努力將下面的安全轉換爲PDO。有任何想法嗎?謝謝你的幫助。將mysql_fetch_assoc轉換爲PDO
function getSlug($param)
{
$query = mysql_query("SELECT * FROM articles WHERE slug = '$param'") OR die(mysql_error());
return mysql_fetch_assoc($query);
}
我正在努力將下面的安全轉換爲PDO。有任何想法嗎?謝謝你的幫助。將mysql_fetch_assoc轉換爲PDO
function getSlug($param)
{
$query = mysql_query("SELECT * FROM articles WHERE slug = '$param'") OR die(mysql_error());
return mysql_fetch_assoc($query);
}
連接和連接管理¶
Connections are established by creating instances of the PDO base class. It doesn't matter which driver you want to use; you always use the PDO class name. The constructor accepts parameters for specifying the database source (known as the DSN) and optionally for the username and password (if any).
<?php
$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass); <<== This is the PDO DATABASE OBJECT
function getSlug($param)
{
$sth = $dbh->prepare("SELECT * FROM articles WHERE slug = ?"); <<== First you need to prepare it
$sth->execute(array($param)); <<== Then execute it using params
$result = $sth->fetchAll(PDO::FETCH_ASSOC); <<== Then USe PDO Constant to get Associative array
return $result; <<<== Then return it
}
?>
現在我得到這個錯誤:「解析錯誤:語法錯誤,意外的」: '在第6行「。 – aphextwig
Edited.I錯過了':'在'PDO :: FETCH_ASSOC' – underscore
感謝您的更新,但現在我得到另一個錯誤:「致命錯誤:調用第5行上的非對象的成員函數prepare()」 – aphextwig
你讀過的PDO文檔? –
首先你需要'準備'查詢。然後用'PARAMS'執行它。然後你可以使用'PDO:FETCH_ASSOC'返回結果常量 – underscore