Hi everyone, I need a wee bit of help with the following.

I am calling all country names from a db table and echo-ing out each country name in a list format.

$query = "select * from countries order by Country Desc"; 

$result = mysql_query($query) or die(mysql_error());


while($row = mysql_fetch_array($result)){
    echo $row['Country'];
    echo "<br />";
}

this gives me a list of country names from the database, what I would like to do is have the list look like the following.

["country name 1", "country name 2", "country name 3", "country name 4"]

How can I acheive this, thanks

Dani AI

Generated

As pointed out, producing a JSON array is the right way to get the output shown in the opening post. A few practical improvements beyond the quick example already given: select only the Country column instead of SELECT *, use a modern database extension (PDO or mysqli) because the old mysql_* functions are deprecated/removed, and send a JSON content-type header so consumers parse the response correctly.

A compact, modern pattern using PDO (fetch the single column directly, preserve Unicode, handle errors) looks like this:

<?php
$dsn = 'mysql:host=localhost;dbname=your_db;charset=utf8mb4';
$pdo = new PDO($dsn, 'db_user', 'db_pass', [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);

$stmt = $pdo->query('SELECT DISTINCT Country FROM countries ORDER BY Country ASC');
$countries = $stmt->fetchAll(PDO::FETCH_COLUMN);

header('Content-Type: application/json; charset=utf-8');
echo json_encode($countries, JSON_UNESCAPED_UNICODE);

A few troubleshooting notes that build on 's original query: use DISTINCT if duplicate rows exist; switch ASC/DESC to control sort direction; ensure the connection/DB use utf8mb4 so accented characters aren’t mangled; and wrap DB operations in try/catch for graceful failure reporting. If the JSON will be embedded inside HTML rather than returned as an API response, take care to escape or safely insert it on the page instead of printing raw JSON into markup.

Recommended Answers

All 2 Replies

Sounds like you want json_encode()

$countries = array ();
while($row = mysql_fetch_array($result)){
    $countries[] = $row['Country'];
}
echo json_encode($countries);

Oh yes, that is perfect, cheers

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.