一个简单的PHP语法问题

时间:2010-07-30 12:00:35

标签: php

我只想从下面的代码中了解?:指定的内容,如果有人向我解释下面的代码,我将不胜感激。谢谢

$country = empty($_POST['country']) ? die ("ERROR: Enter a country") : mysql_escape_string($_POST['country']); 

5 个答案:

答案 0 :(得分:3)

它被称为三元运算符,只是此代码的简写

if (empty($_POST['country']))
{
  die ("ERROR: Enter a country");
}
else
{
  $country = mysql_escape_string($_POST['country']);
}

<强>语法:

condition ? used if true : used if false;

或者你可以做作业:

variable = condition ? used if true : used if false;

更多信息:

http://www.tuxradar.com/practicalphp/3/12/4

答案 1 :(得分:1)

见:

PHP syntax question: What does the question mark and colon mean?

它是PHP以及其他语言的三元运算符。

答案 2 :(得分:1)

$country = empty($_POST['country']) ? die ("ERROR: Enter a country") :

我想这个脚本接受POST方法发送的表单中的数据。如果country变量为空,请退出脚本并显示错误消息。

mysql_escape_string($_POST['country']);

此函数应从给定变量返回转义值。因此它应该写成这样

$country = mysql_escape_string($_POST['country']);

此处有更多信息:http://php.net/manual/en/function.mysql-escape-string.php

答案 3 :(得分:1)

$country = empty($_POST['country']) ?
           die ("ERROR: Enter a country") :
           mysql_escape_string($_POST['country']);

如果表达式empty($_POST['country'])的评估结果为true,则会评估die ("ERROR: Enter a country")(并将结果分配给$country,但事实是{{1}暂停脚本执行)。

另一方面,如果die()评估为empty($_POST['country']),则会评估false,并将结果分配给mysql_escape_string($_POST['country'])

答案 4 :(得分:1)

测试条件:如果HTML FORM中的变量为空,则打印出“错误:输入国家/地区”,否则设置变量国家/地区安全字符..