如何有效地检索大量数据库设置作为 PHP 变量?
目前,我的脚本的所有设置都位于我“包含”的 PHP 文件中。我正在将这些设置(大约 100 个)移动到名为“设置”的数据库表中。然而,我正在努力寻找一种有效的方法将它们全部检索到文件中。
设置表有 3 列:
- ID(自动增量)
- 名称
- 值
两个示例行可能是:
admin_user john
admin_email_address [email protected]
我能想到检索每个设置的唯一方法是这样的:
$result = mysql_query("SELECT value FROM settings WHERE name = 'admin_user'");
$row = mysql_fetch_array($result);
$admin_user = $row['value'];
$result = mysql_query("SELECT value FROM settings WHERE name = 'admin_email_address'");
$row = mysql_fetch_array($result);
$admin_email_address = $row['value'];
等等
这样做会占用很多 的代码并且可能会很慢。
有更好的办法吗?
Currently all of my script's settings are located in a PHP file which I 'include'. I'm in the process of moving these settings (about 100) to a database table called 'settings'. However I'm struggling to find an efficient way of retrieving all of them into the file.
The settings table has 3 columns:
- ID (autoincrements)
- name
- value
Two example rows might be:
admin_user john
admin_email_address [email protected]
The only way I can think of retrieving each setting is like this:
$result = mysql_query("SELECT value FROM settings WHERE name = 'admin_user'");
$row = mysql_fetch_array($result);
$admin_user = $row['value'];
$result = mysql_query("SELECT value FROM settings WHERE name = 'admin_email_address'");
$row = mysql_fetch_array($result);
$admin_email_address = $row['value'];
etc etc
Doing it this way will take up a lot of code and will likely be slow.
Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
100个设置?一次性加载它们。这根本不需要时间。您绝对不想一次加载它们。
如果您需要以某种方式对这些进行划分,根据您需要的方式,您可以在表格上放置一个类别或其他内容,然后加载特定类别中的所有设置。
我建议将其抽象为某种对象:
这样,在您尝试访问一个对象之前,不会加载设置:
100 settings? Load them all at once. That will take no time at all. You absolutely do not want to load them one at a time.
If you need to compartmentalize these somehow, depending on how you need to do it, you could put a category or something on the table and then just load all the settings in a particular category.
What I would suggest is abstracting this behind an object of some kind:
This way the settings aren't loaded until you try and access one:
好吧,我似乎已经弄清楚了:
虽然我不热衷于使用 eval(),但它有效,但我认为这是唯一的方法。
我现在想知道是否许多主机都禁用了 eval() 。有什么想法吗?
Well I seem to have figured it out:
It works although I wasn't keen on using eval(), but I think it's the only way.
I'm now wondering whether many hosts have eval() disabled. Any thoughts?