Shrestha Sunil
Shrestha Sunil

Reputation: 329

creating array dynamically

I am trying to creates the array dynamically like below using php

 $data =    array(
  array("date" => "1/2/2012", "sentstatus" => "0", "mobile" => "14578998"),
      array("date" => "21/2/2012", "sentstatus" => "1", "mobile" => "14668998"),
      array("date" => "1/5/2012", "sentstatus" => "1", "mobile" => "14598998"),
      array("date" => "1/6/2012", "sentstatus" => "0", "mobile" => "14578748"),
);

Below is my PHP code that insert the sql server data into array but the problem is that it the array is formed of only last result set row of the database table. I am not getting the idea to insert all database table row into array as shown above:

 $sql = "SELECT [start_date_time],[sent_status],[mobile_number] ,[play_file] 
         FROM [slice].[dbo].[tbl_message_detail] ";
 $res = odbc_exec($con,$sql) or die(odbc_error());
 $rows = odbc_num_rows($res);

 while($row = odbc_fetch_array($res))
  {     
 $data =  array(
         array("Date_Time" => $row['start_date_time'], "Send_Status" => $row['sent_status'], "Mobile_Number" => $row['mobile_number'], "play_file" => $row['play_file'])
    );
   }

Upvotes: 0

Views: 102

Answers (3)

Damien Pirsy
Damien Pirsy

Reputation: 25435

You're overwriting the $data variable at each round of the loop. This:

$data = array();
while($row = odbc_fetch_array($res))
{     
 $data[] = array("Date_Time" => $row['start_date_time'], 
                 "Send_Status" => $row['sent_status'], 
                 "Mobile_Number" => $row['mobile_number'], 
                 "play_file" => $row['play_file']
           );
}

should work as you need

Upvotes: 1

k102
k102

Reputation: 8079

try this code:

while($row = odbc_fetch_array($res))
{     
  $data[] =  array("Date_Time" => $row['start_date_time'], 
                   "Send_Status" => $row['sent_status'], 
                   "Mobile_Number" => $row['mobile_number'], 
                   "play_file" => $row['play_file']);
}

Upvotes: 1

Tim M.
Tim M.

Reputation: 54377

You are getting only the last row because you are creating a new array with every iteration. Declare $data outside of the while loop.

Upvotes: 1

Related Questions