【问题标题】:Heredoc string php problemsHeredoc字符串php问题
【发布时间】:2014-10-04 05:04:01
【问题描述】:

我正在尝试使用 heredoc 撰写电子邮件内容。我不知道如何访问从以前的一些 sql 查询中存储的变量并将它们插入到文本中。

这是 sql 查询:

$week=mysql_query('SELECT `Name`, `fname`, `Marca` FROM `personal` WHERE (`Responsabil`='.$id.') AND (`Protectie`>="'.$CurrentDate.'") AND (`Protectie`<"'.$WeekDate.'") AND (`Notificat`!=1)');
$exp=mysql_query('SELECT `Name`, `fname`, `Marca` FROM `personal` WHERE (`Responsabil`='.$id.') AND (`Protectie`<"'.$CurrentDate.'") AND (`Notificat`!=1)');
$week=mysql_fetch_assoc($week);
$exp=mysql_fetch_assoc($exp);

还有问题:

$content=<<<EMAIL
We inform you that the following people:
$week['Name'] $week['fname']
$exp['Name'] $exp['fname']
are due for inspection.
EMAIL;

我需要在此处插入由查询产生的所有名称。查询已经过测试并且可以正常工作。

【问题讨论】:

  • 你遇到了什么错误?
  • 解析错误:语法错误,意外的 '' (T_ENCAPSED_AND_WHITESPACE),需要标识符 (T_STRING) 或变量 (T_VARIABLE) 或数字 (T_NUM_STRING)。它不喜欢 $week 之类的 ' '....
  • EMAIL; 位删除后有空格。

标签: php mysql sql heredoc


【解决方案1】:

您需要将结果变量用大括号括起来,以使它们在 heredoc 字符串中正确显示:

$week['Name'] = "Bloggs";
$week['fname'] = "Joe";

$exp['Name'] = "Doe";
$exp['fname'] = "Jane";

$content = <<<EMAIL
We inform you that the following people:
{$week['Name']} {$week['fname']}
{$exp['Name']} {$exp['fname']}
are due for inspection.
EMAIL;

var_dump($content);

返回:

string(87) "We inform you that the following people: Bloggs Joe Doe Jane are due for inspection."

【讨论】:

  • 这行得通,但是我如何发布 $week 的漏洞内容让我们说。如果 $week 是一个名称数组。
  • 你可以从数组结果中构建一个字符串:$str = ""; foreach ($week['Name'] as $name) {$str .= $name;} 然后在它循环之后,将$str 放在 Heredoc 中
  • @iswinky 你也可以在数组中使用$week[fname] 引号是多余的
  • @insanebits 不知道!是从 5.4 开始的吗?
  • 这行得通。我现在唯一的问题是换行符(\n)没有显示在文本中
【解决方案2】:

试试这个,

$content=<<<EMAIL
We inform you that the following people:
{$week['name']} {$week['fname']}
{$exp['name']} {$exp['fname']}
are due for inspection.
EMAIL;

请注意,这只会打印一条记录,如果您想显示结果集中的所有记录,则需要在结果集上循环。

【讨论】:

    猜你喜欢
    • 2011-11-26
    • 2020-02-24
    • 2019-11-21
    • 2019-04-07
    • 1970-01-01
    • 2011-04-02
    • 2020-12-01
    • 2011-04-29
    相关资源
    最近更新 更多