简体   繁体   English

如何将MYSQL_FETCH_ARRAY结果存储到不同的变量中

[英]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. 在使用mysql select语句之后,假设我得到两条记录,我想要做的是将这些结果存储到两个不同的变量中。 Let say, I get 4,5 after select statement. 比方说,我在select语句后得到4,5。 I want to save 4 and 5 into different variables. 我想将4和5保存到不同的变量中。

$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访问您的数据:

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 不要使用mysql_ *函数,因为从PHP 5.5.0开始不推荐使用它们

Keys of array from mysql_fetch_array are always field names from table. mysql_fetch_array中的数组键始终是表中的字段名。 Every loop you push a new line from query result. 每个循环都会从查询结果中推出一个新行。

As aaron says you can conserve it pushing values into array. 正如aaron所说,你可以保存它将值推入数组。 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']; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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