简体   繁体   中英

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.

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

可能不在主题之列,但可以考虑使用PDO扩展来学习MySQL,因为它可以帮助您避免常见的错误,并可以帮助您迁移到更复杂的解决方案,例如Zend_DB,Doctrine或Propel

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM