简体   繁体   English

有没有比这种方法更好的方法来在MySQL中执行SELECT查询并在PHP中对其进行排序?

[英]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. 我只是在学习PHP / MySQL,我要做的很多事情就是将以前插入数据库的数据显示给用户的浏览器。 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. 现在,当我在一个数据库中只有3列时,以上述方式进行操作就不是问题了,但是如果我要处理一个具有更多列的大型数据库该怎么办。

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. 我有点a,专业人士以某种更有效的方式做到这一点,他们可能会遍历他们从中选择的表以查找其具有的所有列,并将它们与变量自动关联。 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: 如前所述, extract将比我最初的解决方案更好:

$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 我必须说,我了解您正在尝试做的事情,但为什么不这样做:D

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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