为何需两次执行SQL语句?fetchColumn使用疑问
$res2 is empty without the second execute()? Your confusion is totally understandable—this behavior boils down to how PDO’s result set cursors work with the fetchColumn() method. Let’s break it down clearly:
What fetchColumn() actually does
Every time you call fetchColumn($index):
- It pulls the value from the specified column of the current row in the result set.
- It immediately moves the result set cursor to the next row.
Let’s walk through your code step by step (assuming your query returns exactly one row of data, which seems likely here):
- After the first
execute(), the cursor starts at the very beginning of the result set (before the first row). - When you run
$res = $stmt->fetchColumn();(default index0), it grabs thefirstNamefrom the first (and only) row, then shifts the cursor past this row—now the cursor is at the end of the result set, with no more rows left to read. - If you skip the second
execute()and call$res2 = $stmt->fetchColumn(1);right after, there are no rows left to pull data from. So it returnsfalse, which appears empty when concatenated with a string.
Why re-running execute() fixes it
Calling execute() again re-runs your SQL query and resets the entire result set. This moves the cursor back to the start of the data, so fetchColumn(1) can now grab the lastName from that first row before advancing the cursor again.
A better approach for your use case
Since you need two columns from the same row, using fetchColumn() twice isn’t the right tool. Instead, fetch the full row as an array and extract the values you need:
$sql = "SELECT firstName , lastName FROM People WHERE born='1934'"; $stmt = $db->prepare($sql); echo "<p>Execute the SQL-statement:<br><code>$sql</code><p>"; $stmt->execute(); // Fetch the entire row as an associative array $row = $stmt->fetch(PDO::FETCH_ASSOC); if ($row) { $ANSWER = $row['firstName'] . " " . $row['lastName']; }
This way you get both values in one go, no need to re-execute the query or juggle cursor positions.
内容的提问来源于stack exchange,提问作者Vince Mazuka

