Function to put the entire database table in an array

I wrote a function to print a database table into an array like this

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

My function:

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;
                        }

Something is wrong with my function. Any help is appreciated for my problem. thanks in advance

+3
source share
3 answers

I'm not sure if your function will receive all rows returned by the database. mysql_fetch_array()returns only one row. So the for loop is pretty pointless.

Instead, you need something similar instead of a for loop.

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

By the way, if you still want to use a for loop, you can try something like this. But what would be the point?while loop works fine for this.

$numRows = mysql_num_rows($query);
for($i = 0; $i < $numRows; $i++) {
  $allArrays[$i] = mysql_fetch_array($query);
}
0
source

, ( )

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;
}

(: print_r)

+2

This seems to work, but it seems to hit the target of the relational database. Why not just serialize your data and write it to a file?

0
source

Source: https://habr.com/ru/post/1737624/


All Articles