skip to Main Content

I am New to php and programming as well.

I have a variable in an SQL query-based while loop. Below

switch ($command) {
    case "country":
        $statement = "SELECT w_id,w_name FROM wards ORDER BY w_id ASC";
        $dt = mysqli_query($conn, $statement);
        while ($result = mysqli_fetch_array($dt)) {
            echo $result1 = "<option value=" . $result['w_id'] . ">" . $result['w_name'] . "</option>";
        }
        break;
}

exit();

The loop works just fine butthe variable contains duplicate strings.

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

2

Answers


  1. That means you have duplicate rows in your DB, if you’d like to retrieve unique values, you could try a "group by" statement.

    SELECT w_id, w_name FROM wards GROUP BY  w_name, w_id ORDER BY w_id ASC
    

    It’s a good practice indenting your code so you don’t get confused in later reviews 🙂

    Login or Signup to reply.
  2. Change your sql query by using distinct keyword.

    SELECT DISTINCT w_id, w_name FROM wards ORDER BY w_id ASC
    

    This will prevent fetching duplicate rows from your DB.
    Please see the documentation: https://www.w3schools.com/sql/sql_distinct.asp

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search