Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL - Select specific value from a fetched array

Tags:

arrays

php

mysql

I have a small problem and since I am very new to all this stuff, I was not successful on googling it, because I dont know the exact definitions for what I am looking for.

I have got a very simple database and I am getting all rows by this:

while($row = mysql_fetch_array($result)){
    echo $row['id']. " - ". $row['name'];
    echo "<br />";
}

Now, my question is: how do I filter the 2nd result? I thought something like this could work, but it doesnt:

$name2= $row['name'][2];

Is it even possible? Or do I have to write another mysql query (something like SELECT .. WHERE id = "2") to get the name value in the second row?

What I am trying to is following:

-get all data from the database (with the "while loop"), but than individually display certain results on my page. For instance echo("name in second row") and echo("id of first row") and so on.

like image 480
r0skar Avatar asked Oct 19 '11 12:10

r0skar


2 Answers

If you would rather work with a full set of results instead of looping through them only once, you can put the whole result set to an array:

$row = array();

while( $row[] = mysql_fetch_array( $result ) );

Now you can access individual records using the first index, for example the name field of the second row is in $row[ 2 ][ 'name' ].

like image 139
JJJ Avatar answered Oct 16 '22 23:10

JJJ


$result = mysql_query("SELECT * FROM ... WHERE 1=1");
while($row = mysql_fetch_array($result)){
/*This will loop arround all the Table*/
    if($row['id'] == 2){
    /*You can filtere here*/
    }

    echo $row['id']. " - ". $row['name'];
    echo "<br />";
}
like image 38
javi_moralesf Avatar answered Oct 17 '22 01:10

javi_moralesf