Kent
Kent

Reputation: 13

Is there a better way to do SELECT queries in MySQL and sort them in PHP than this way?

I am just learning PHP/MySQL, one this I am having to do a lot is displaying data that was previously inserted into the database out to the user's browser. So I am doing this:

$select = mysql_query('SELECT * FROM pages');

while ($return = mysql_fetch_assoc($select))
{
     $title = $return['title'];
     $author = $return['author'];
     $content = $return['content'];
}

then I can use these variables through out the page. Now, doing it the above way isn't an issue when I only have 3 columns in a database but what if I am dealing with a huge database with many more columns.

I have a nagging feeling that the pros do it in some more efficient way where they maybe loop through the table they are selecting from to find all columns it has and associate them with variables automatically. Is that the case? or is the above how you guys do it too?

EDIT

Thanks for the answers guys, they have helped me to explain what I had in mind better. The reason why I am trying to do this, is so that I have to write less.

Is it possible to get the names of the columns of a table automatically. Then have a loop that will automatically create the variables naming them the same as the column names:

some type of loop 
{

   $nameofcolumn = $return['$nameofcolumn'];

}

This way I don't have to manually repeat myself:

 $title = $return['title'];
 $author = $return['author'];
 $content = $return['content'];

Because normally I just name the variables the same as the table column names.

Upvotes: 0

Views: 140

Answers (2)

Nazariy
Nazariy

Reputation: 6088

Might be off topic but consider to learn MySQL using PDO extension as it would help you to avoid common mistakes and would help you to migrate to more complex solutions like Zend_DB, Doctrine or Propel

Upvotes: 0

fresskoma
fresskoma

Reputation: 25781

As pointed out extract would be better than my initial solution:

$select = mysql_query('SELECT * FROM pages');

while ($return = mysql_fetch_assoc($select))
{
     extract($return, EXTR_OVERWRITE);
}

Both solutions will overwrite any already existing variables with the name of a column though.

But I am not quite getting why anyone would want to do that. I must say that I understand what you are trying to do, but not why :D

Upvotes: 1

Related Questions