开发者

Array or Assoc?

开发者 https://www.devze.com 2023-01-25 23:45 出处:网络
I\'m trying to store data from a MySQL table into an PHP array variable. Currently, I\'ve got this: $row = $db->query(\"SELECT * FROM settings\");

I'm trying to store data from a MySQL table into an PHP array variable.

Currently, I've got this:

$row = $db->query("SELECT * FROM settings");
$sysconfig = $row->fetch_array();

the database scheme is as such:

property value
online     1
autoupd    1
setting    1

etc.

How should I write the above code, so that I can use the value, for the property in the data, i.e.

$sysconfig['online'] would retu开发者_如何转开发rn "1"?

A var_dump($sysconfig) yields this

array(6) { [0]=> string(6) "online" ["property"]=> string(6) "online" [1]=> string(1) "1" ["propertyid"]=> string(1) "1" [2]=> string(1) "1" ["value"]=> string(1) "1" }

A print_r($sysconfig) yields this

Array ( [0] => online [property] => online [1] => 1 [propertyid] => 1 [2] => 1 [value] => 1 )

Thanks


fetch_array returns both associative and enumerated arrays. You can specify it to return only assoc array by adding MYSQL_ASSOC parameter. Or you may use fetch_assoc method.

UPD: For your scheme you have only 'property' and 'value' columns, so you need to rewrite your select query with joins or iterate through dataset like this:

$sysconfig = array();
while ($line = $row->fetch_assoc())
    $sysconfig[ $line['property'] ] = intval($line['value']);

//$sysconfig['online'] == 1


what does the class you're using look like? I'd usually suggest using something like:

$sysconfig = mysql_fetch_assoc($row);

which would return an array for that row. Does your $db class have a method for this? What happens if you do the following:

print_r($sysconfig);

You should see a breakdown of the returned array, which will highlight which methods you can use to access the data within.

EDIT:

Replace this line:

$sysconfig = $row->fetch_array();

With:

while($data = $row->fetch_array()){
    $sysconfig[$data['property']] = $data['value'];
}

You should then be able to access the results as you wanted.


$result = $db->query("SELECT * FROM settings");

while ($row = mysql_fetch_assoc($result)) {
    echo $row["online"];
    echo $row["autopd"];
    echo $row["setting"];
     // etc.
}


$row = $db->query("SELECT * FROM settings");
while($data = $row->fetch_array())
   $sysconfig[$data['property']] = $data['value'];
0

精彩评论

暂无评论...
验证码 换一张
取 消