【问题标题】:PHP code for quotation marks and ifelse statement - correct syntax?引号和 ifelse 语句的 PHP 代码 - 语法正确吗?
【发布时间】:2011-07-15 12:57:26
【问题描述】:

这是一个 PHP 页面,它显示使用 JOIN 的查询结果 (基于教程中的一个并适用于我的数据库):

    <?php
$connection = mysql_connect("localhost", "root", "PASSWORD") or die("Error connecting to database");
mysql_select_db("products", $connection);
$result = mysql_query("SELECT * FROM buyers LEFT JOIN products USING (id);", $connection) or die("error querying database");
$i = 0;
while($result_ar = mysql_fetch_assoc($result)){
?>
<table>
<tr <?php if($i%2 == 1){ echo "class='body2'"; }else{echo "class='body1'";}?>>
<td>
<?php echo $result_ar['buyer_name']; ?></td>
<td>
<?php echo $result_ar['manufacturer']; ?>
</td>
<td>
<?php $result_ar['product_name'] = ($result_ar['product_name'] == '')? $result_ar['product_name'] : '"' . $result_ar['product_name'] . '"'; echo $result_ar['product_name']; ?>
</td>
</tr>
</table>
<?php
$i+=1;
}
?>

但是,这里的问题不是连接,而是这个 PHP 编码:

<?php $result_ar['product_name'] = ($result_ar['product_name'] == '')? $result_ar['product_name'] : '"' . $result_ar['product_name'] . '"'; echo $result_ar['product_name']; ?>

我试过了,它显示了以下内容(此问题开头代码的完整结果):

John Zanussi "1500 Washing Machine"
James Hotpoint "3000 Washing Machine"
Simon Hotpoint

我很惊讶它的工作,这只是一个测试语句,看看代码是否工作。

http://www.w3schools.com/php/php_if_else.asp 是我的工具。

如果我是正确的,这意味着它将把 product_name 列中的任何数组放在引号中,但如果该列是空白的,那么它将显示引号.

只是检查我是否正确 - 在这里尝试复习我的 PHP 技能!

【问题讨论】:

  • 结合 w3school 对 mysql 的建议,您也将提高黑客技能!开玩笑,但有时它是一个糟糕的资源。
  • 是的 w3schools 资源很差。不过,这不是对这个问题投反对票的理由。 OP 要求专家澄清三元运算符的功能。

标签: php mysql if-statement echo


【解决方案1】:

你是对的。你代码中的三元运算相当于:

// If the product_name isn't empty, surround it in quotes.
if (!empty($result_ar['product_name']))
{
  $result_ar['product_name'] = "\"{$result_ar['product_name']}\"";
}

在这里使用三元运算有点令人困惑,因为第一种情况(空值)仍然会导致空值。更多时候,您会看到相反的情况——用于为空变量创建默认值的三元运算。

在回显变量的上下文中,您可以将其缩短为该表达式。在回显之前无需重新分配变量。您可以回显三元运算的结果。

// Based on your version...
echo ($result_ar['product_name'] == '')? $result_ar['product_name'] : '"' . $result_ar['product_name'] . '"';

// Clearer version with the empty case last rather than first...
echo !empty($result_ar['product_name']) ? "\"{$result_ar['product_name']}\"" : "";

要使用三元运算来分配一个类(例如,可能有粗体文本),您可以在表格单元格中使用类似这样的内容:

<td class='<?php echo $result_ar['product_name'] == "Zanussi" ? "special_bold_class" : "regular_class";?>'>

结果是:

<td class='special_bold_class'>

【讨论】:

  • 谢谢!这可以用于其他任何事情,例如如果值等于 Zanussi 等而不是其他制造商,则使文本变为粗体?
  • @avenas8808 请参见上面添加的示例。
猜你喜欢
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 2019-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-08
  • 1970-01-01
相关资源
最近更新 更多