Re: Equivelant to mysql_fetch_row for normal array

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Dave M G wrote:
Jochem, Tul, Nicolas,

Thank you for your help.

I must be doing something wrong with how my array is generated. It's actually just a MySQL result, but because it is returned from a function, it does not seem to behave as I would expect a MySQL result should.

I'm trying the foreach function and key values, but I'm clearly not quite getting it right. Perhaps there is something about my code which is wrong. So I'm presenting what I hope is all the relevant parts:

public function getData($row, $type, $column, $match) {
$query = "SELECT " . $row . " FROM " . $type . " WHERE " .$column . " = " . $match;
echo "query = " . $query . "<br />";
$result = mysql_query($query);
$data = mysql_fetch_array($result);
return $data;
}

foreach($elements as $key => $val){
echo "val[type] = " . $val[type] . "<br />";
echo "val[resource] = " . $val[resource] . "<br />";
}


What I'm getting back doesn't make sense. I can't go all the way into my code, but $val[type] should be a string value containing the words "Article" or "Text".

But instead, I get:
val[type] = 2
val[resource] = 2

Am I still not doing the foreach correctly?

--
Dave M G

First of all, you're using invalid syntax. You should have $val['type'] rather than $val[type].

Second of all, mysql_fetch_array returns only a single row, $elements. This is an array. From there, you're asking foreach to return each element of the array as $val. So each time through the foreach loop, $val will have the contents of that element. The element isn't an array, it's a scalar. So you're taking a scalar and trying to treat it like an array.

You really should read the manual, the pages for all these functions describe EXACTLY what they do.

Remember that mysql_fetch_array returns an associative array. You can refer to the SQL fields by their names. So if your select query was "SELECT foo, bar FROM mytable", after doing a mysql_fetch_array you could do this:

echo $row['foo'] . "<br />";
echo $row['bar'] . "<br />";

Regards, Adam.

--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux