简体   繁体   English

PHP-Foreach循环获取结果

[英]PHP - Foreach loop get results

I have this function below, that should list all the country codes from my database, that is present, and then count how many times each country code is present: 我在下面有此功能,该功能列出数据库中存在的所有国家代码,然后计算每个国家代码出现的次数:

function getAvailableCountries(){
    global $dbh;

    $stmt = $dbh->prepare("SELECT country_code,country_name FROM users WHERE country_code!='NA' AND country_name!='NA'");
    $stmt->execute();
    $rows = $stmt->fetchAll();

    foreach ($rows as $row){
        $countryCode =  $row["country_code"];
        $countryName =  $row["country_name"];   
    }

    print "<option value='$countryCode'>$countryName</option>";

}

the $countryCode variable consists of: USUSUSUSCA (since US is present 4 times in my database and CA is present one time) (The $countryName variable consists of the name of the countries, same format as above.) $countryCode变量包含: USUSUSUSCA (因为在我的数据库中US出现了4次,CA出现了一次)($ countryName变量包含国家/地区的名称,格式与上述相同。)

The function then returns this: 然后该函数返回以下内容:

<option value="US">United States of America</option>

My question is though, how can I get the available countries from my database, and then print them out, so each country is only present once ? 我的问题是,如何从数据库中获取可用的国家/地区,然后将其打印出来,所以每个国家/地区只出现一次

Add DISTINCT to your query: DISTINCT添加到您的查询中:

$stmt = $dbh->prepare("SELECT DISTINCT country_code,country_name FROM users WHERE country_code!='NA' AND country_name!='NA'");

You should also add print in your loop: 您还应该在循环中添加print

foreach ($rows as $row){
    $countryCode =  $row["country_code"];
    $countryName =  $row["country_name"];   
    print "<option value='$countryCode'>$countryName</option>";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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