might be a basic one but i wrote a function that selects all from a dbtable in backend. But in front end, i want to use it with foreach to display results wherever i want.
Array(
[0] => Array
(
[stockCatID] => 1
[stockCatName] => Copper
[stockParentCat] => 0
)
[1] => Array
(
[stockCatID] => 2
[stockCatName] => Zinc
[stockParentCat] => 0
)
)
When I send resultset to my front-end page, this array shows up. So I can’t basically play it with:
<?php
$r = getAll("stockcategories");
foreach($r as $k=>$v) {
echo ("<p><strong>$k</strong>: $v</p>");
}
With above result array iu outputs:
0 = Array1 = Array
Added: I don’t want to echo from backend function.
So finally it is my function:
<?php
function getAll ($tableName,$orderBy="", $limit="") {
$orderBy = $orderBy == "" ? $orderBy : (" ORDER BY =\"".$orderBy."\" ");
$limit = $limit == "" ? $limit : (" LIMIT =\"".$limit."\" ");
$q = mysql_query("SELECT * FROM $tableName $orderBy $limit");
if (!$q) { die('Could not connect: ' . mysql_error());} else { $num=mysql_numrows($q);
if ($num != 0 ) {
while($r = mysql_fetch_assoc($q)) {
$rArray[] = $r;
}
mysql_free_result($q);
return $rArray;
} else { echo '<span class="notification n-error">No Record Found</span>'; return false; }
}
?>
Thanks for any help.
$rArrayis a 2 dimensional array but you are accessing it in only one dimension. You need nestedforeachloops. The outer loop iterates over each row returned, and the inner iterates over the columns in each row:Update a function to iterate over both dimensions:
Call it as: