There is a database with a table and entries in it. It is necessary to write data from the database to the array and output them in a table.

A piece of code where an entry to the array is represented

<?php mysql_connect("localhost", "root", "") or die(mysql_error()); mysql_select_db("bospor_abons") or die(mysql_error()); $strSQL = "SELECT * FROM abons_table"; $rs = mysql_query($strSQL); $abons = array(); while($rows = mysql_fetch_array($rs)) { $abons[] = array_values($rows); } var_dump($abons); mysql_close(); ?> 

It turns out this: enter image description here

I can not understand why all the data is duplicated. And how is all this normal output to the table so that all the fields of one DB column are displayed in one row? As far as I understand it is necessary to use the foreach loop, but how exactly - I cannot understand. Help me please.

  • It is possible, as an option, to print directly from while() . - mix

2 answers 2

The values ​​are duplicated, since you use mysql_fetch_array for sampling, whose second parameter is $ result_type and by default is MYSQL_BOTH. This means that it will return values ​​for both associative and numeric indices.

You can use instead:

mysql_fetch_array($rs, MYSQL_ASSOC)

or for numeric indices

mysql_fetch_array($rs, MYSQL_NUM)

You can also use the following instead:

mysql_fetch_assoc($rs)

or

mysql_fetch_row($rs)

However, I strongly recommend that you stop using the deprecated methods and look at MySQLi or PDO.

  • Thank you for help. On account of PDO I will consider. - luckydutch

The code below does not do this so that all the fields in one DB column are displayed in one row . It prints one record from the database in a row of the table.

 echo '<table>'; forech ($abons as $row) echo '<tr><td>' . implode('</td><td>', $row) . '</td></tr>'; echo '</table>'; 
  • thanks for the help - luckydutch
  • Yes, there is nothing complicated. good luck - splash58