Page 1 of 1

Getting values from MySQL array

Posted: Sat Jan 30, 2010 6:54 am
by moodbuilder
Hi everyone, I 'm having trouble when getting the value from the MySQL DB, databse as shown:

table name: animal
name |type |number
------------------------
John | cat | 5
John | dog | 6
John | fish | 3
Adam | bird | 4

I want to show all types(under John) from an array by:

$query = "SELECT * FROM `animal` WHERE `name`='John' ";
$result = mysql_query( $query) or die ("didn't query");
while ($row = mysql_fetch_array($result)) {
print $row[1];}

But I'm getting catdogfish, is there any way I can get it seperate so i can assign them in different variable? many thx

Re: Getting values from MySQL array

Posted: Sat Jan 30, 2010 9:11 am
by social_experiment
Try :

Code: Select all

<?php
while ($row = mysql_fetch_array($result)) {
 print $row['type']."<br />";
}
?>

Re: Getting values from MySQL array

Posted: Sat Jan 30, 2010 10:03 am
by moodbuilder
It shows the results! thx but if I want to assign each each value to variable like

$type1 = cat;
$type2 = dog;
$type3 = fish;

I tried

$type1 = $row['type'][0];
$type2 = $row['type'][1];
$type3 = $row['type'][2];

but it doesn;t seem working, any thoughts? many thx again!

Re: Getting values from MySQL array

Posted: Sat Jan 30, 2010 10:25 am
by AbraCadaver

Code: Select all

while ($row = mysql_fetch_array($result)) {
    $types[] = $row['type'];
}

Re: Getting values from MySQL array

Posted: Sat Jan 30, 2010 11:22 am
by moodbuilder
Thx, I tried:

$types[] = $row['type'];
print $types[0];

and I get:
//catcatcat

print $types[1];
//dogdog

print $types[2];
//fish

Don;t know why [0] and [1] it gives trible and double value? thx again!

Re: Getting values from MySQL array

Posted: Sat Jan 30, 2010 11:27 am
by AbraCadaver

Code: Select all

while ($row = mysql_fetch_array($result)) {
    $types[] = $row['type'];
}
 
echo $types[0].'<br>';
echo $types[1].'<br>';
echo $types[2].'<br>';
 
foreach($types as $type) {
    echo $type.'<br>';
}