当我确切知道我需要哪一列时,在 PHP、MySQL 中使用 select
现在我使用这段代码:
$welcome_text = mysql_query("SELECT * FROM `text` WHERE `name` = 'welcome'");
while ($row = mysql_fetch_array($welcome_text, MYSQL_ASSOC)) {
echo $row['content'];
}
如果我确切地知道我需要哪一列,是否可以在没有 WHILE 的情况下使用它? 像这样的:
$welcome_text = mysql_query("SELECT 'content' FROM `text` WHERE `name` = 'welcome'");
echo $welcome_text;
谢谢
now i use this code:
$welcome_text = mysql_query("SELECT * FROM `text` WHERE `name` = 'welcome'");
while ($row = mysql_fetch_array($welcome_text, MYSQL_ASSOC)) {
echo $row['content'];
}
Is it possible to use it without WHILE if i know exactly which one column i need?
Something like this:
$welcome_text = mysql_query("SELECT 'content' FROM `text` WHERE `name` = 'welcome'");
echo $welcome_text;
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
mysql_query
进行查询,返回结果集。mysql_fetch_array
从结果集中获取第一行。当然,如果您愿意,您可以缩短代码,但这可能会使您的代码更难以调试和维护。
详细、清晰的代码>一行“炫耀”代码。
包括“以防万一”检查:
在打印之前双重确保您拥有所需内容的良好做法。
最后,请确保在用户提交的数据进入数据库之前对其进行清理。如果您不打算使用准备好的语句,至少使用mysql_real_escape_string。
实践安全 SQL,使用准备好的语句来防止SQL 注入。
mysql_query
makes the query, returns a result set.mysql_fetch_array
fetches the first row from the result set.Of course, you can shorten your code if you want, but this may make your code more difficult to debug and maintain.
Verbose, clear code > one-liner 'show-off' code.
Including 'just-in-case' checking:
Good practice to make doubly sure you have what you need before printing it.
Finally, please make sure you sanitize user-submitted data before it goes into your database. If you're not going to use prepared statements, at least use mysql_real_escape_string.
Practice safe SQL, wear a prepared statement to prevent SQL Injections.
我会为此编写一个函数:
现在您可以使用:
注意: 您可以抛出异常而不是返回
null
值。但很难说哪个更好,这可能取决于您的编程风格。I would write a function for this:
And now you can use:
Note: You may throw an exception instead of returning the
null
value. But what is better is hard to say and it may depend on your programming style.这不完全是一回事。在第一个示例中,您将迭代多个行,而不是列。
除非您确定只有一行名为
welcome
,否则您仍然需要循环。你是对的,当你只需要某些列时,你不应该
select *
,这是浪费。换句话说,您应该使用仅稍作修改的:
That's not entirely the same thing. In your first sample, you're iterating over multiple rows, not columns.
Unless you're certain that there's only one row with the name
welcome
, you're still going to need the loop.You are right that you shouldn't
select *
when you only need some of the columns, it's wasteful.In other words, you should use the only slightly modified: