简体   繁体   中英

In PHP5, how do I create an associative array from a database query?

I am creating a class for an application "backbone" and I need this function to query the db, and return a multidimensional to look like this:

$myArray = ("name"=>"John", "dob"=>"January 5, 1955");

Of course the data for the array is from a database query. but, "name" and "dob" would be the database column name and "John" and "January 5, 1955" would be the value of the column

Here is my code:

public function getFrame($id) {
    $getFrameQuery = "SELECT * FROM " . DB_FRAMETABLE . "WHERE `fhid`=" . $this->quote_smart($id);
    $getFrameRecord = $db->query_first($getFrameQuery);          
}

Any help is greatly appreciated!

Josh

What database wrapper are you using? They usually provide a way to retrieve a row into an associative array.

mysql_fetch_assoc(), for example

From your comment to the other answer, the wrapper you are using provides a ->fetch_array() method that returns the data structure you are looking for.

Looks like you would need to change your code to use something like

$result = $db->query($getFrameQuery);
$data = $db->fetch_array($result);

This isn't a multidimensional array. Just a regular associative array.

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