htmlentities() 期望参数 1 为字符串


htmlentities() expects parameter 1 to be string

>im 尝试将数据从数据库获取到文本字段中:

$fothersq=("SELECT others FROM january");
$fothers=mysql_query($fothersq);
<input type="text" placeholder="0" name="febothers" size="11" value="<?php if(@$fothers){echo htmlentities(@$fothers);} ?>">

但是我在文本字段中遇到了此错误。


警告:htmlentities(( 期望参数 1 为 string, resource in C:''xampp''htdocs''CashFlow''febprev.php116

同样在另一个文本字段中,我使用此编码只是为了测试:

<input type="text" name="febbonus" size="11" placeholder="0" value="<?php if(@$fbonus){echo (@$fbonus);} ?>"> 

我得到了这个错误:

资源 ID #7

有什么想法吗?

这些错误准确地告诉您问题所在:

警告:htmlentities(( 期望参数 1 是字符串、资源 在 C:''xampp''htdocs''CashFlow''febprev.php 第 116 行给出

而这个:

资源 ID #7

这两个错误都告诉您mysql_query返回资源。此时它不是一个字符串。您需要处理该资源并对其采取行动。试试这个。

$fothersq=("SELECT others FROM january");
$fothers=mysql_query($fothersq);
while ($row = mysql_fetch_assoc($fothers)) {
  echo sprintf('<input type="text" placeholder="0" name="febothers" size="11" value="%s">', (!empty($row['others'] ? htmlentities($row['others']) : '')));
}

另外,请注意,我将<input type="text"> HTML元素放在一个echo中,因为您提供的代码作为直接的PHP或HTML或两者的混合几乎没有意义。

编辑:基于原始海报可能会被三元运算符混淆的评论,这是我答案的修改版本,它将实现相同的目标,但方式稍微简单一些:

$fothersq=("SELECT others FROM january");
$result=mysql_query($fothersq);
while ($row = mysql_fetch_assoc($result)) {
  $fothers = '';
  if (!empty($row['others']) {
    $fothers = htmlentities($row['others']);
  }
  echo '<input type="text" placeholder="0" name="febothers" size="11" value="' . $fothers . '">';
}

既然你运行了这个

$fothers=mysql_query($fothersq);

现在$fothers将不是一个字符串。这将是一个resource

但是您正在将$fothers传递到需要字符串的htmlentities()中。

需要更正的要点:

  • htmlentities(( 函数将字符转换为 HTML 实体。因此,它需要一个字符串,在您的情况下,您的传递资源。

  • 你得到Resource id #7因为你没有拿任何东西。执行后,使用 mysql_fetch_array 获取行。

试试这个:

$fothersq=("SELECT others FROM january");
$fothers=mysql_query($fothersq);
while ($fetch = mysql_fetch_array($fothers)) {
?>
<input type="text"  name="febothers" size="11" value="<?php echo (isset($fetch[0])) ?  htmlentities("$fetch[0]") : ''?>">
<?php
}