Reputation: 3523
I apologize in advance if this is a trivial question, but I did check the PHP manual and I can only seem to find bits on fetching multiple rows (which I have no problem with). Consider the below code:
$fetch = $db->prepare("
SELECT col1, col2
FROM table
WHERE col0 = '1'
");
$fetch->execute();
//SQL request made, returns 1 row, 2 columns
echo $fetch->fetchColumn(); //perfect
echo $fetch->fetchColumn(1); //doesn't work
//only one column can be fetched per SQL request
From my limited understanding of PDO, I would need to do something like the below:
$fetch->execute(); //execute 1st time
echo $fetch->fetchColumn(); //perfect
$fetch->execute(); //execute 2nd time
echo $fetch->fetchColumn(1); //perfect
//or
$fetch->execute(); //execute only once
foreach($fetch as $fetcher) {} //ugly
echo $fetcher["col1"]; //perfect
echo $fetcher["col2"]; //perfect
The first method is slow, but the second lacks finesse. I know I could put the logic within the foreach()
loop, but other than looking a little cleaner, it does the same thing since the request returns only one row (foreach()
will iterate only once).
I want to reduce SQL load as much as possible if just to be efficient. The actual processing difference is thousandths of a second long. But I also want code to be clean and concise.
Upvotes: 2
Views: 1804
Reputation: 562731
If you want to be efficient about SQL traffic, then just execute and fetch once:
$fetch->execute(); //execute only once
$row = $fetch->fetch(PDO::FETCH_ASSOC);
echo $row["col1"]; //perfect
echo $row["col2"]; //perfect
Upvotes: 4