問題描述
我盡量不感到沮喪,但我最近了解到 mysql_*
在 PHP 中已被棄用.我決定學習如何使用 PDO.
I'm trying not to get frustrated, but I've recently learned that mysql_*
is deprecated in PHP. I've decided that I would learn how to use PDO.
今天下午我剛剛在看它,使用它連接到數據庫很容易,但后來我想用它獲取一行并將該行保存為由列名索引的數組(同樣的方式正如函數 mysql_fetch_array
所做的那樣).我想不出它來挽救我的生命.
I've just been looking at it this afternoon, and connecting to the database using it was easy, but then I wanted to fetch a row with it and save the row as an array indexed by the column names (the same way as the function mysql_fetch_array
did). I can't figure it out to save my life.
我會發布我的代碼來澄清,我確信它很簡單(所有編程錯誤總是很簡單),但我肯定做錯了什么.
I'll post my code to clarify, and I'm sure it is something simple (all programming errors are always simple), but I am definitely doing something wrong.
// Connect to the database
$host = $_PARAM["DatabaseServer"];
$db = $_PARAM["MainDatabase"];
$dbuser = $_PARAM["DatabaseUser"];
$dbpass = $_PARAM["DatabasePass"];
try
{
$Database = new PDO("mysql:host=$host;dbname=$db", $dbuser, $dbpass);
}
catch (PDOException $e)
{
echo "There was an unexpected error. Please try again, or contact us with concerns";
}
$stmt = $Database->prepare("SELECT * FROM users WHERE username=?");
$stmt->execute(array($sUserCook));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo $row["username"];
推薦答案
fetchAll
做它所說的:它獲取查詢的所有結果.由于它獲取了大量結果,因此您將獲得一個索引數組.
fetchAll
does what it says: it fetches all results for a query. Since it fetches a lot of results, you'll get an indexed array.
fetch
會執行您可能正在尋找的操作:它為查詢獲取一個結果.如果您要將 mysql_*
代碼轉換為 PDO,最快的方法是使用此方法而不是 mysql_fetch_assoc
.
fetch
does what you might be looking for if you want only one row: it fetches one result for a query. If you're converting mysql_*
code to PDO, the quickest way would be to just use this method instead of mysql_fetch_assoc
.
如果您仍然使用 fetchAll
:您的代碼可能看起來像這樣:
If you're still going with fetchAll
: your code would probably just look like this:
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
echo $row['username'];
}
就像我說的,如果您只是將遺留代碼轉換為 PDO 代碼,將所有查詢更改為準備好的語句并替換以下內容可能會更容易:
Like I said, if you're just converting legacy code to PDO code, it might be easier to just change all queries to prepared statements and replace the following:
mysql_fetch_assoc($result)
->$stmt->fetch(PDO::FETCH_ASSOC)
mysql_num_rows($result)
->$stmt->rowCount()
while ($row = mysql_fetch_assoc($result)) {}
->foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {}
這篇關于如何使用 PDO 獲取一行的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!