How to Display SQL Query in an Array

Asked

Viewed 1,664 times

0

I have a question. When I run a Select Count in the database it displays everything straight. But how to display it the same way using PHP?

select country, count(*) as quantidade from customer group by country

inserir a descrição da imagem aqui

$sql=mysql_query("select country, count(*) as quantidade from customer group by country");

And then I don’t know.

3 answers

3


You can do it this way:

$arr = array();
$sql=mysql_query("select country, count(*) as quantidade from customer group by country");
while ($row = mysql_fetch_array($sql)) {
    $arr [$row ["country"]] = $row["quantidade"];
}

In this way, an array will be created where the name of the countries are the keys and the quantities are the values.

In this link there is more information about the command mysql_fetch_array.

1

try using the command mysql_fetch_array:

$sql=mysql_query("select country, count(*) as quantidade from customer group by country");
$exibe = mysql_fetch_assoc($sql);
            echo $exibe["country"];

Then just put in a loop and do some tests.

  • I’m trying to build the loop but without success.

0

Utilize print_r with the return of the database within HTML tags <pre> as follows:

$query=mysql_query("select country, count(*) as quantidade from customer group by country");
$valores = mysql_fetch_assoc($query);
echo '<pre>';
print_r($valores);
echo '</pre>';
  • When I use the print_r it only displays the first line.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.