警告:为foreach()提供的参数无效

时间:2014-11-14 10:06:29

标签: php mysql

在下面的php代码中,我收到了上述错误。 $strings将来自数据库的字段存储为数组。那么为什么会出现这个错误呢?有人可以告诉我这个问题的解决方案吗。

$db_selected = mysql_select_db("chatter",$con);
$mvsql="Select body from feed";
$str=mysql_query($mvsql,$con);$i=0;
while($strings=mysql_fetch_array($str)){
echo $strings["body"] . "<br>";
}
require_once __DIR__ . '/../autoload.php';
$sentiment = new \PHPInsight\Sentiment();
foreach ($strings as $string) {

    // calculations:
    $scores = $sentiment->score($string);
    $class = $sentiment->categorise($string);

    // output:
    echo "String: $string\n";
    echo "Dominant: $class, scores: ";
    print_r($scores);
    echo "\n";
}

4 个答案:

答案 0 :(得分:1)

在while循环中添加此行,并使用foreacn:

$stringsArr[] = $strings["body"];
  • 不要使用mysql_函数,因为它们已被弃用。请改用mysqli_PDO

答案 1 :(得分:1)

while($strings=mysql_fetch_array($str)):循环的最后一次迭代,mysql_fetch_array返回false(不再有行)。因此,在此循环之后,当您进入foreach循环时,$stringfalse。只需在while循环内执行每行的指令。

$db_selected = mysql_select_db("chatter",$con);
$mvsql="Select body from feed";
$str=mysql_query($mvsql,$con);$i=0;
require_once __DIR__ . '/../autoload.php';
$sentiment = new \PHPInsight\Sentiment();
while($strings=mysql_fetch_array($str)){
    $body = $strings['body'];

    // calculations:
    $scores = $sentiment->score($body);
    $class = $sentiment->categorise($body);

    // output:
    echo "String: $body\n";
    echo "Dominant: $class, scores: ";
    print_r($scores);
    echo "\n";
}

请同时阅读这篇文章:Why shouldn't I use mysql_* functions in PHP?,非常有用。

答案 2 :(得分:0)

您迭代直到mysql_fetch_array($str)返回false。即直到$strings不再是数组。 foreach期望$strings成为数组。

答案 3 :(得分:0)

foreach启动时,

$ strings将为FALSE。 这是因为它高于它。这个循环将循环遍历所有记录,直到mysql_fetch_array($ str)返回FALSE,从而终止循环。

您可能应该将foreach代码放在while循环中,或者使用while循环来收集所需的项目并循环遍历foreach循环中的项目。