tags:

views:

67

answers:

3

I have written a function to print database table to an array like this

$db_array=  
 Array(
    ID=>1,
    PARENTID =>1,
    TITLE => LIPSUM,
    TEXT =>LIPSUM
    )

My function is:

function dbToArray($table)
                        {
                          $allArrays =array();
                          $query = mysql_query("SELECT * FROM $table");
                          $dbRow = mysql_fetch_array($query);
                            for ($i=0; $i<count($dbRow)  ; $i++)
                                {
                                   $allArrays[$i] =  $dbRow; 
                                }
                            $txt .='<pre>';
                            $txt .= print_r($allArrays);
                            $txt .= '</pre>';
                            return $txt;
                        }

Anything wrong in my function. Any help is appreciated about my problem. Thanks in advance

A: 

It looks like it'll work, but kind of defeats the purpose of a relational database.. Why not just serialize your data and write it to a file?

Brendan Long
Hi Brendan;I do this (serialize data and write it to a file?). But im looking for a global function to do this.
It looks like it will only show the first row over and over again.
Sinan
+2  A: 

Seems like you are trying to print a table (not a database)

function printTable($table){
   $allRows = array();
   $query = mysql_query("SELECT * FROM $table");
   while($row = mysql_fetch_array($query)){
      $allArrays[] =  $row; 
   }
   $txt ='<pre>';
   $txt .= print_r($allRows, true);
   $txt .= '</pre>';

   echo $txt;

   return $txt;
}

*(Edit: fixed missing second parameter in print_r)*

PHP_Jedi
This prints empty output
`print_r( $allRows );` should be `print_r( $allRows, true );`. See http://php.net/print_r
jwandborg
Thats correct, I updated the code. Thanks
PHP_Jedi
A: 

Im not sure your function will get all the rows returned by the database. mysql_fetch_aray() returns only one row. So the for loop is pretty pointless.

Instead you should something like this instead of the for loop.

while($row = mysql_fetch_array($query){
  $allArrays[] = $row;
}

by the way if you still want to use the for loop you could try something like this. But what would be the point? the while loop works perfectly for this.

$numRows = mysql_num_rows($query);
for($i = 0; $i < $numRows; $i++){
  $allArrays[$i] = mysql_fetch_array($query);
}
Sinan
output is:Array( [0] => Array ( [0] => 1 [ID] => 1 [1] => 0 [PARENTID] => 0 [2] => 1 [CATID] => 1 [3] => Newss [CATNAME] => Newss [4] => 1 [BASEID] => 1 [5] => 2010-03-19 01:10:51 [TARIH] => 2010-03-19 01:10:51 [6] => News Head [BASLIK] => News Head [7] => Lorem ipsum dolor [MANSET] => Lorem ipsum )) ))BTW I want a function to print arrays...
just change your for loop with one of above. And add a second parameter 'true' to print_r like @jwandborg said.
Sinan