Search This Blog

Monday, December 27, 2010

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

Programmer Question

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.



Find the answer here

No comments:

Post a Comment

Related Posts with Thumbnails