This is my first question here on StackOverflow, and quite frankly I'm fairly new to PHP. Just to give you a brief heads-up ;)
I'm building an OOP-based website, in a 3-tier architecture. In my data abstraction layer, I have an object I called DbAdapter, which contains all functions necessary to communicate with the database. One of these functions is the one below: read($sql), which takes an SQL query and stores the result in a two-dimensional array.
For this, it uses two nested for-loops (one for the rows and one for the columns per row). And while the iterator $i increments as usual, somehow the last element of the array is overwritten.
I have absolutely no idea how this is possible, so the mistake I made must be extremely stupid.
Anyone care to help out a newbie?
Thanks in advance, Sam
public $loadedRows;
public function read($sql)
{
if ($this->connect())
{
$result = mysql_query($sql);
if ($result)
{
$totalRows = mysql_num_rows($result);
$totalFields = mysql_num_fields($result);
for ($i = 0; $i < $totalRows; $i++)
{
for ($j = 0; $j < $totalFields; $j++)
{
$fieldName = mysql_field_name($result, $j);
$loadedFields["$fieldName"] = mysql_result($result, $i, $fieldName);
}
$this->loadedRows[i] = $loadedFields;
}
$this->closeConnection();
return $this->loadedRows;
}
}
}
you just forgot $ before i
$this->loadedRows[$i]
and this code should be way shorter:
That's ALL.
and to catch these errors yourself, you should set error reporting level to
E_ALL
to do that you can add this line
in your config file.
It will tell PHP to watch such mistakes (using undefined constant i in this case) and notify you