简体   繁体   中英

PHP or MySQL - how to display only one table row out of many with the same value

I wrote this simple code which outputs first letters of values (in this case names of companies) stored in every each table row:

include_once('db.php'); //connection with database

$result = mysql_query("SELECT distinct Name FROM companies ORDER BY Name");

while ($row = mysql_fetch_array($result)) {
$letter = substr($row[0], 0, 1);     
echo '<p><a href="#">' . $letter . '</a>/p>';
} 

The companies table contains names of companies and the $letter variable contains first letter of those names.

Apparently in the companies table there are many names starting with the same letter.

Now, how to display only one letter "A", one letter "B", one letter "C" etc. out of many letters "A", "B", "C" etc.?

Why don't you put that in your query itself?

Modify the query to

SELECT distinct SUBSTRING(Name,1,1) FROM company ORDER BY SUBSTRING(Name,1,1)

Here's the sql fiddle

To do this in PHP you can create a blank array and push the first letter of each company onto the array if it doesnt already exist like this:

include_once('db.php'); //connection with database

$result = mysql_query("SELECT distinct Name FROM companies ORDER BY Name");

$letters = array();

while ($row = mysql_fetch_array($result)) {
    if(!in_array(substr($row[0], 0, 1), $letters)){
        array_push($letters, substr($row[0], 0, 1));
    }    
} 

foreach($letters as $l){
    echo '<p><a href="#">' . $l . '</a></p>';
}

If you want to show all letters of the alphabet even if a company doesnt start with that letter you can use the PHP range function like this:

foreach (range('a', 'z') as $letter) {
    echo '<p><a href="#">' . $letter . '</a></p>';
}

Use this SQL statement

SELECT DISTINCT SUBSTR(Name,1,1) FROM companies ORDER BY Name;

This will return distinct values from first letter of Names;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM