Jump to content

php!? How to get data from DB into ASSOC ARRAY?

- - - - -

  • Please log in to reply
1 reply to this topic

#1
Stasonix

Stasonix

    Learning Programmer

  • Members
  • PipPipPip
  • 82 posts
  • Programming Language:C++, PHP, JavaScript, Delphi/Object Pascal, Pascal
  • Learning:C++, PHP, JavaScript, Delphi/Object Pascal
for example I have a table:

CREATE TABLE `db_test`.`tb_test` (

`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,

`carname` INT NOT NULL ,

`drivername` INT NOT NULL ,

`flag_test` TINYINT NOT NULL

) ENGINE = MYISAM ;

then assoc array on outside must have look like this:
$MyCar = array();

$MyCar[0] = array(

    'name' => "toyota",

    'voditel' => array("alex"),

    'dr_test' => array(1),

);
well next $MyCar[1] must have data from next record of table tb_test, how to get it in?

#2
gregwarner

gregwarner

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 853 posts
  • Location:Arkansas
Use this:

$query  = "SELECT * FROM tb_test";

$result = mysql_query($query);

$row = mysql_fetch_assoc($result);

mysql_fetch_assoc() returns a row from your table as an associative array using the column names as the keys. It returns null if there are no more rows to read.

If you want to read all the rows into an array, you can use a while loop like this:

$rows = array();

while ($row = mysql_fetch_assoc($result)) {

    $rows[] = $row;

}


Hofstadter's Law: It always takes longer than you expect, even when you take into account Hofstadter's Law.

– Douglas Hofstadter, Gödel, Escher, Bach: An Eternal Golden Braid





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users