简体   繁体   中英

Create a php array with keys and values from mysql query

I'm trying to store my mysql query in an array like this :

$arr = array ( "field1"=>"value" , "field2"=>"value" , "field3"=>"value" , ... );

I've tried this but don't work like I need :

$row_selectProduct = array();
$sResult = $db->query( 'SELECT * FROM tbl' )    

while ( $aRow = $sResult->fetch_assoc() )
{
        $sInfo = $sResult->fetch_field();
        // General output
        $row_selectProduct[ $sInfo->name ] = $aRow;
}

$sResult->close();

Thx for help

EDIT : Sorry for misunderstanding... I'd like to name keys by the field name in database. I try to reproduce this :

$result = array();

while ($row_selectProduct = mysql_fetch_assoc($selectProduct));
{

    $row_array= array();

$row_array['field_name1_In_DB'] = $row_selectProduct['field_name1_In_DB'];
$row_array['field_name2_In_DB'] = $row_selectProduct['field_name2_In_DB'];
$row_array['field_name3_In_DB'] = $row_selectProduct['field_name3_In_DB'];
$row_array['field_name4_In_DB'] = $row_selectProduct['field_name4_In_DB'];
$row_array['field_name5_In_DB'] = $row_selectProduct['field_name5_In_DB'];
...

array_push($result,$row_array);

};

Using PDO connection functions , it's quite simple --

foreach($db->query('SELECT field_name1,field_name2 FROM table') as $row) {
    echo $row['field_name1'].' '.$row['field_name2']; //etc...
}

Here's a good tutorial for PDO in PHP if you want more.

while ( $aRow = $sResult->fetch_assoc() )
{
        foreach($aRow as $fieldname => $fieldvalue) {
             $row_selectProduct[$fieldname] = $fieldvalue;   
        }

}

but you will overwrite your $row_selectedProduct with every record and the var at the end will only have stored the last record

if you would like to have all results in one array you should:

$results = array();
while ( $aRow = $sResult->fetch_assoc() )
{
        $results[] = $aRow;

}

if you know that there will be only one result you need only:

$result = $sResult->fetch_assoc();

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