Ykstate
Ykstate

Reputation: 35

Display unique values in for loop javascript

I'm trying to display unique value in for loop per below. The data is retrieved from mysql. Currently, it's displaying all the values in this column (Book Name) but just want to show just unique value and remove any duplicated values from displaying.

<?php
$i=0;
while($rows=mysql_fetch_array($result))
{
$roll1[$i]=$rows['bkname'];
$i++;
}
$total_elmt=count($roll1);
?>
<form method="POST" action=" ">
<select name="sel1" id="sel1">
<option value="Select Book Name">Book Name</option>
<?php 
for($j=0;$j<$total_elmt;$j++)
{
?><option><?php 
echo $roll1[$j];
?></option><?php
}
?>
</select>
</form>

Upvotes: 0

Views: 481

Answers (3)

Kevin
Kevin

Reputation: 41875

Instead of removing duplicates in the PHP, you could just use a DISTINCT clause in your query:

<?php

$db = new mysqli('localhost', 'username', 'password', 'database_name');
// $sql = 'SELECT DISTINCT(bkname) FROM your_table_name';
$sql = 'SELECT * FROM your_table_name GROUP BY bkname';
$query = mysqli_query($db, $sql);

?>

<form method="POST" action="">
    <select name="sel1" id="sel1">
        <option disabled selected>Book Name</option>
        <?php while($row = mysqli_fetch_assoc($query)): ?>
            <option value="<?php echo $row['bkname']; ?>"><?php echo $row['bkname']; ?></option>
        <?php endwhile; ?>
    </select>
</form>

Obligatory Note:

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Ref: https://stackoverflow.com/a/12860140/3859027

Upvotes: 1

scotty
scotty

Reputation: 559

This can be handled in your query easiest most likely by using the DISTINCT keyword. If your query is something like

SELECT bkname FROM Books;

Instead you would do

SELECT DISTINCT bkname FROM Books;

If you don't want to modify your dataset though, and want an array of unique values from just a column in the dataset you can insert those values into an array utilizing it as a hashmap. The key will ensure uniqueness and eliminate duplicates.

while($rows=mysql_fetch_array($result)){
    $roll1[$rows['bkname']] = $rows['bkname'];
}

Upvotes: 0

Todd
Todd

Reputation: 5454

How about PHPs array_unique function?

<?php
$input = array("Tale of two cities", "Tale of two cities", "A brief history of time", "Hop on Pop");
$noduplicates = array_unique($input);
var_dump($noduplicates);
?>

Upvotes: 0

Related Questions