-2

In the following php code, I am getting the above error. $strings stores the fields coming from database as an array. So why is this error coming? Can someone tells me the solution for this problem, please.

$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";
}
Nima Soroush
  • 12,242
  • 4
  • 52
  • 53
kratika gupta
  • 91
  • 1
  • 1
  • 4
  • 1
    `while($strings=mysql_fetch_array($str))`: the last iteration of the loop, mysql_fetch_array returns `false` (no more rows). So after this loop, when you go in your foreach, `$string` is `false`. –  Nov 14 '14 at 10:09

4 Answers4

1

Add this row in your while loop, and use the foreacn on this:

$stringsArr[] = $strings["body"];
  • Do not use mysql_ functions, because they are deprecated. Use mysqli_ or PDO instead.
vaso123
  • 12,347
  • 4
  • 34
  • 64
1

while($strings=mysql_fetch_array($str)): the last iteration of the loop, mysql_fetch_array returns false (no more rows). So after this loop, when you go in your foreach loop, $string is false. Just execute your instructions inside the while loop, for each row.

$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";
}

Please also read this post: Why shouldn't I use mysql_* functions in PHP? , very useful.

Community
  • 1
  • 1
0

You iterate until mysql_fetch_array($str) returns false. I.e. until $strings is no longer an array. foreach expects $strings to be an array.

Oswald
  • 31,254
  • 3
  • 43
  • 68
0

$strings will be FALSE when the foreach starts. This is because of the while above it. This loop will loop through all records, till mysql_fetch_array($str) returns FALSE and thus terminates the loop.

You should probably put the foreach code inside the while loop or use the while loop to collect the items you need and loop through those in the foreach loop.

Yaron
  • 11
  • 4