How to fetch one row from database
-
I found this lovely function in our code base. I just love how the while loop is beeing used. Maybe it's expecting a lot of rows, but the function's name and the binding of @ItemId somehow tells me that there should only be one result.
The code has been anonymized a little.
<?php
public function GetItemFromDb($ItemId)
{
global $DbConn;
$Conn = $DbConn->GetConnection();
$Conn->Init('GetItem');
$Conn->Bind('@ItemId', $ItemId);
$Conn->Exec();
$item = false;
$SettingsSet = false;
while ($Conn->Next())
{
if (!$SettingsSet)
{
$this->ItemId = $Conn->res['ItemId'];
/* Removed some $this->{value} get some value */
$SettingsSet = true;
}
$item = new Item();
$item->SetValues($Conn->res);
}
return $item;
}
?>
-
-
It continues to bemuse me the length that which PHP coders will go to in order to cram any sort of database query into a while loop. It's like the Third Commandment of PHP is "Thou Shalt Use a While Loop to Query a Database" (and I shudder to think what the others might be).
They'll avoid for loops, preferring instead to simulate them with a while loop and a counter variable. And, as here, they'll use a while loop even when they only expect, and want, at most one record.
'Scuse me,I have to go wash my hands.