Get dynamic mySQL table column with PHP

1.3k views Asked by At

Normally all the basic PHP-MYSQL-SELECT tutorials are based on this code

$query = "SELECT * FROM table_name";
$result = mysql_query($query);

$num = mysql_num_rows($results);
if ($num > 0) {
    while ($row = mysql_fetch_assoc($result)) {
        // You have $row['ID'], $row['Category'], $row['Summary'], $row['Text']
    }
}

but for this I need to know the column name like 'ID', 'Category', 'Summary' or 'Text'. And if I add in phpmyadmin a new column like 'Email', I also have to add $row['Email'] to the php script.

How can I make this step dynamic?

2

There are 2 answers

3
Dexa On

regarding this particular question, for what do you need rows? if you just want to print them do print_r($row) and they'll be there, if you want to do something with them make foreach loop like this

foreach($row as $k=>$cell)
{
    //do something with cell
}

but as lot of other people would tell you, use PDO.

3
Rafael On

You can use mysql_fetch_array() instead of mysql_fetch_assoc() and you will be able to use indexes instead of names, however, in any case, order is not guaranteed unless you define it yourself in your query, but depending of what you want to do with the results, it can help.

Standard nag: Use MySQLi.