"Börni" <b.reiter@onlinehome.de> wrote in message
news:crcbct$53p$1@online.de...[color=blue]
> Richards Noah (IFR LIT MET) wrote:[color=green]
> >
> > Please show us how you're accessing the elements in the array. The[/color][/color]
general[color=blue][color=green]
> > form is:[/color]
> Well i'm just doing it like this:
> $result = $mysqli->query($sql);
> $array = $result->fetch_assoc();
> var_dump($array);
>
> The var_dump shows me just one element in the array. But it should be two.
>[/color]
You are misinterpreting what mysql_fetch_assoc() (and other calls such as
mysql_fetch_row() and mysql_fetch_array()) do. They return only one row at
a time, and each row they return is an array of all fields for that row.
So, when you say (as taken from your original post):
"SELECT column FROM table WHERE column1="3" AND column2="1""
You are selecting only 1 piece of data (column) for every row returned.
Run this code instead:
$result = $mysql_query($sql);
while($array = mysql_fetch_assoc($result))
var_dump($array);
This will var_dump each row. The while loop will continue until FALSE is
returned by mysql_fetch_assoc().
I would suggest reading up on these functions
(
http://www.php.net/manual/en/functio...etch-assoc.php,
http://www.php.net/manual/en/functio...etch-array.php,
http://www.php.net/manual/en/functio...fetch-row.php).
[color=blue]
>[color=green]
> > Again, please provide an example. I'm not sure exactly how you are[/color][/color]
doing[color=blue][color=green]
> > it, but the usual way is:
> >[/color]
> Ok this problem is solved, but still its weird. Look at the example.
>
> $test = array("id" => "92");
> var_dump($test);
> foreach ($test as $id) {
> echo $id['id']."<br />";
> }
>
> Trying this your output is "9"[/color]
Which is the intended behavior :) Here's what you are doing:
1) On each iteration, $id becomes the _value_ of one of the array elements.
So, on the first iteration, it becomes "92".
2) when you say $id['id'], you are using indexing on a string. So 'id' (as
the index) is evaluated as an integer, which is 0.
3) You access $id[0], which is the first character of the string "92",
which is "9".
Try it with any other string ("$id['ilikepie']" or "$id['astring']") and it
will yield the same result. Try it with $id[0] and $id[1] and you'll get
"9" and "2", respectively.
[color=blue]
>
> $test = array("id" => "92");
> var_dump($test);
> foreach ($test as $id) {
> echo $id."<br />";
> }
>
> And now its "92".[/color]
This is the correct way to use foreach. As I mentioned before, if you need
to access both the key and value, use foreach like:
foreach($test as $id = > $value)
{
print("Key of $id has Value of $value");
}
This will print:
Key of id has Value of 92.
If you need more explanation, consult the doc (
http://www.php.net/foreach).