简体   繁体   中英

How to store MYSQL_FETCH_ARRAY result into different Variables

I am unable to find a solution for a simple problem, it's a shame. After using mysql select statement, let say I get two records, what I want to do is to store these results into two different variables. Let say, I get 4,5 after select statement. I want to save 4 and 5 into different variables.

$query = mysql_query("SELECT test_id FROM test WHERE MONTH(created)='$res_month'");

while($abc = mysql_fetch_array($query)) {

    echo $abc; 

}

Push the records to an array like this:

$data = array();
while($abc = mysql_fetch_array($query)) {
    $data[] = $abc;
}

$first = $data[0]['test_id'];
$second = $data[1]['test_id'];
// etc ...

You can use a foreach to access your data:

foreach($data as $value){
    //$value
}
$query = mysql_query("SELECT test_id FROM test WHERE MONTH(created)='$res_month'");
$a = array();
while($abc = mysql_fetch_array($query)) {
$a[] = $abc['test_id']; 
}

To access values

foreach($b as $a){
     echo $b;
 }

Don't use mysql_* function, as they are deprecated as of PHP 5.5.0

Keys of array from mysql_fetch_array are always field names from table. Every loop you push a new line from query result.

As aaron says you can conserve it pushing values into array. You can do it with a two dimension array too if table have a primary key. This way you can find lines by index.

$query = mysql_query("SELECT test_id,field2,field3 FROM test WHERE MONTH(created)='$res_month'");


$data=array();
while($abc = mysql_fetch_array($query)) 
{

// two dimension array

     $data[$abc['test_id']]['test_id']=$abc['test_id'];
     $data[$abc['test_id']]['field2']=$abc['field2'];
     $data[$abc['test_id']]['field3']=$abc['field3'];

// view values

     echo $abc['test_id']; 
     echo $abc['field2']; 
     echo $abc['field3']; 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM