0

I am running a while/foreach on a mySQL database and an array to check if it exists or not. It's supposed to loop 170 times but it loops over 12000 times. Why is that?

$my_rows = array();
while($row = mysql_fetch_assoc($run_query)){

    $my_rows[] = $row;
    foreach($my_rows as $row){
        if(in_array_r($row['name'], $products)){
            echo "Exists";
        } else {
            echo "Does not exist";
        }
    }
}
Camilo Payan
  • 181
  • 7
user1996496
  • 972
  • 2
  • 10
  • 24
  • remove the hole foreach, each `while` $my_rows grows and each time the `foreach` is running – ob_start Jan 04 '16 at 20:47
  • Hah! Thanks :) If you add an answer I'll gladly accept it! – user1996496 Jan 04 '16 at 20:51
  • Please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). [These extensions](http://php.net/manual/en/migration70.removed-exts-sapis.php) have been removed in PHP 7. Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [PDO](http://php.net/manual/en/pdo.prepared-statements.php) and [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) and consider using PDO, [it's really pretty easy](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Jan 04 '16 at 22:20

2 Answers2

3

What should be happening here is that you assign the result of mysql_fetch_assoc to $my_rows and then loop over the contents of $my_rows. One loop. One of those loops doesn't need to exist.

$my_rows = mysql_fetch_assoc(...);
foreach($my_rows as $row){ ...do stuff here... }
Camilo Payan
  • 181
  • 7
2
$my_rows = array();

while($row = mysql_fetch_assoc($run_query)){

    $my_rows[] = $row;

    if(in_array_r($row['name'], $products)){

        echo "Exists";

    } else {

        echo "Does not exist";

    }

}
ob_start
  • 276
  • 1
  • 3
  • Why should the OP try this? A ***good answer*** will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO. – Jay Blanchard Jan 04 '16 at 22:20