0

I have a variable in an SQL query-based while loop. e.g:

$sql = mysql_query("SELECT * FROM table");
while($row=mysql_fetch_array($sql)){

    echo $row['row'];

}

The while loop is functional and works, however the variable contains duplicate strings.

How do I prevent duplicate row variables echoing in my while loop with PHP?

Note: This is a PHP question, not an SQL question.

zak
  • 151
  • 3
  • 14
  • It depends. Is the data ordered a particular way, i.e. are all of the duplicates together in the record set? – danmullen Oct 27 '14 at 16:40
  • 2
    This *is* an SQL question. Only select the data you want in the first place. Leave sorting out duplicates up to your database, where it can be handled efficiently. – Brad Oct 27 '14 at 16:40
  • No they are scattered completely randomly – zak Oct 27 '14 at 16:40
  • Assume SQL is impossible – zak Oct 27 '14 at 16:41
  • 1
    Why would SQL be impossible? – Jay Blanchard Oct 27 '14 at 16:42
  • That's not the question, the question is "Is it possible in PHP, and if so, how?" – zak Oct 27 '14 at 16:43
  • Please, [don't use `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php), They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://us1.php.net/pdo) or [MySQLi](http://us1.php.net/mysqli). [This article](http://php.net/manual/en/mysqlinfo.api.choosing.php) will help you decide. – Jay Blanchard Oct 27 '14 at 16:43

1 Answers1

3

Just keep track of each row's unique ID. If you see again, skip it.

$sql = mysql_query("SELECT * FROM table");
$ids = array();
while($row=mysql_fetch_array($sql)){
    if (!isset($ids[$row['id']])) {
        continue;
    }
    $ids[] = $row['id'];
    echo $row['row'];

}

FYI, this is a lot easier and faster if you do it in SQL. But if you must do it in PHP this is how you would do it.

John Conde
  • 217,595
  • 99
  • 455
  • 496
  • 4
    far better to just use the `row[id]` as the key, saving the in_array repetitive searching. `if (!isset($ids[$row['id']]))` – Marc B Oct 27 '14 at 16:46
  • Is this possible when handling string variables? i.e not using their ID, but instead preventing duplication of the actual echoed variable – zak Oct 27 '14 at 17:01
  • @zak You can use any value as long as it is unique. – John Conde Oct 27 '14 at 18:08