Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

php - How to fetch a row with 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.

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"];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 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.

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'];
}

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) {}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...