SQL query sorted by id's with predefined names - php

I have the following SQL table
ID | country_id | name
1 33 test1
2 77 test3
3 33 test5
4 1 test6
5 77 test7
6 33 test8
I want to order this by country_id where each country_id has it's own name (but not in another database).
EX:
$countries = array(
77 => 'Macedonia',
33 => 'Uruguay',
1 => 'Ghana'
);
So the result would be something like this:
ID | country_id | name
4 1 (G hana) test6
2 77 (M acedonia) test3
5 77 (M acedonia) test7
1 33 (U ruguay) test1
3 33 (U ruguay) test5
6 33 (U ruguay) test8

You'll be interested in MySQL's FIELD() function which will allow you to define a custom ORDER BY query:
SELECT
id, country_id, name
FROM
countries
ORDER BY
FIELD(country_id, 77, 33, 1);
FIELD() allows you to define an "ordered list" and then checks what index/position in the list the value you pass in is located at; you can use that to generate your custom ORDER BY.
If you have an array in PHP like you showed with $countries, you could easily generate the query with:
$country_ids = join(',', array_keys($countries));
$fieldClause = 'FIELD(country_id, ' . $country_ids . ');'
Alternatively, if you have a second reference table that contains country names, you could JOIN against that:
SELECT
a.id, a.country_id, a.name
FROM
your_table a
JOIN countries c
on a.country_id = c.id
ORDER BY
c.name;
I would recommend the latter approach since it's more portable.

You need to use the $countries array, sort it and use it in the ORDER BY:
sort($countries);
$order = implode(', ', array_keys($countries));
Now the array is sorted by the values and you can use the keys as the order in FIELD() as shown by newfurniturey:
SELECT id, country_id, name
FROM countries
ORDER BY FIELD(country_id, $order);
However, even with only 3 countries I would create another table and join that.

Related

Display a single columns in while loop using PHP

I searched a lot still could not find satisfactory answer. Please have a look at the sample mysql table below:
id | Name | Country
1 | User1 | India
2 | User2 | India
3 | User3 | India
4 | User4 | Australia
5 | User5 | Australia
I want to display above table in a while loop using PHP, something like below:
Country Name: | Total Members From The Country:
India | 3
Australia | 2
I only want to target and display only one column/field i.e "country". Can anyone please share the query code here so I can proceed with my work and thank you for your time.
Keywords you could search for are GROUP BY and COUNT. The query then should look something like this:
SELECT Country, COUNT(*) FROM Users GROUP BY Country;
This will group all rows by the value of your Country column and count the rows with COUNT which will give you a row for each country with the corresponding count in your table.
You are free to extend the query with a WHERE to filter for specific countries.
Try this query:
SELECT country, count(*) as total_member
FROM your_table
GROUP BY country
You should have something like this as result if you fetch an associative array :
$result = array(
0 => array (
"country" => "India",
"total_member" => 3
),
1 => array (
"country" => "Australia",
"total_member" => 2
)
);
Then just loop throught your result and display what you want :
foreach ($result as $key => $value) {
echo $value['country'] . " | " . $value['total_member'];
}
Adapt so it looks like you want !
Is it what you wanted?

MySQL How to limit amount of rows from JOIN-Query only from first Table and not the Second Table?

I have a two Tables one with Countries and second with Cities.
First Table is Countries
country_id | country_name
Second Table is Cities
country_id | city_id | city_name
I want to limit amount of queries from second Table to 3 Cities. Because one Country have a lot of Cities. I need only 5 Cities.
My Query:
$query = “SELECT c.country_name, p.city_name FROM (SELECT * FROM Cities LIMIT 3) AS p LEFT JOIN Countries as c ON p.county_id = c.county_id”;ter code here
$result = mysqli_query($db, $query);
$my_array = array();
while($row = mysqli_fetch_assoc){
array_push($my_array, $row);
}
If I fill $my_array i get 3 results from Database
My output:
[0] => Array
(
[country_name] => Country 1
[city_name] => City 1
)
[1] => Array
(
[country_name] => Country 1
[city_name] => City 2
)
[2] => Array
(
[country_name] => Country 1
[city_name] => City 3
)
I need something like this
County 1
-----------------------
City 1 of Country 1
City 2 of Country 1
City 3 of Country 1
City 4 of Country 1
City 5 of Country 1
County 2
-----------------------
City 1 of Country 2
City 2 of Country 2
City 3 of Country 2
City 4 of Country 2
City 5 of Country 2
County 3
-----------------------
City 1 of Country 3
City 2 of Country 3
City 3 of Country 3
City 4 of Country 3
City 5 of Country 3
What I do wrong? I use MySQL 5.6.26
Thank you.
Like that?
SELECT city_id, city_name FROM Cities AS p LEFT JOIN Countries AS c ON c.country_id = p.country_id WHERE c.country_id = 'id' LIMIT 0,5

merge Database records when keys match and add values

I wish to select all records from a database and then combine matching keys and also adding their values.
Col1 col2
----- ------
ABC 2
ABA 3
ADD 1
AED 3
ABC 2
ABA 3
ADD 1
AED 3
So i would end up with
array("
ABC => 4,
ABA => 6,
ADD => 2,
AED => 6");
This is basic GROUP BY application:
SELECT Col1, SUM(col2) FROM tbl GROUP BY Col1
See http://sqlfiddle.com/#!2/8d1f8/1 for an example

PHP sql multiple attributes

I have the folowing query that shows my products.
SELECT DISTINCT productsmap.id, attributes_product.waarde,
attributes_product.att_id, productsmap.name, productsmap.category
AS categoryId, brand.naam AS brand, productsmap.sku, categorie.name AS
category, productsmap.price, productsmap.shops
FROM productsmap
INNER JOIN categorie ON productsmap.category = categorie.id
INNER JOIN brand ON productsmap.brand = brand.id
INNER JOIN attributes_product ON productsmap.id = attributes_product.pmapid
WHERE productsmap.category
IN ( 2, 3, 4, 5, 6, 7, 8 )
AND productsmap.shops >0
AND (
productsmap.price >= 3.94
AND productsmap.price <= 204.99
)
AND productsmap.online =1
LIMIT 0 , 30
It gives the folowing results I cropped a bit:
(id) (waarde) (att_id) (name) (categoryId) (brand) (sku)
2 109 1 Name 4 Merk 70000
2 2013 2 Name etc etc etc
2 123 3 Name etc etc etc
3 103 1 Name2 etc etc
3 2012 2 Name2
3 123 3 Name2
4 110 1 3name
4 2013 2 3name
4 102 3 3name
Whit multiple times the same id and name only diffrent att_id and waarde. But i need to add to my query (attributes_product.att_id = 1 and waarde = 109) and (attributes_product.att_id = 2 and waarde = 2013)
But this is not possible because it are diffrent results. How can I solve this issue? Or on what can i search to solve this issue?
It attributes.product are att_id and waarde

Sum php array (created from mysql results) depending on mysql values in another mysql column

One table called 18_7_ChartOfAccounts looks like this:
ID | AccountNumber
-------------
1 | 2310
2 | 2380
3 | 2610
Another table called 2_1_journal looks like this:
ID | Amount | DebitAccount
--------------------------
1 | 26.03 | 2310
2 | 200.00 | 2310
3 | 3.63 | 2380
4 | 119.83 | 2380
5 | 33.86 | 2610
6 | 428.25 | 2610
Aim is to get results that looks like this:
DebitAccount 2310 total is: 226.03
DebitAccount 2380 total is: 123.46
DebitAccount 2310 total is: 462.11
226.03 in this example is total of 26.03 + 200.00
At first mysql code
$query = "SELECT j.Amount, j.DebitAccount FROM 18_7_ChartOfAccounts AS c LEFT JOIN 2_1_journal AS j ON (c.AccountNumber = j.DebitAccount)";
$sql = $db->prepare($query);
$sql->execute();
$data = $sql->fetchAll(PDO::FETCH_ASSOC);
With print_r($data); get long list of arrays like
[31] => Array
(
[Amount] => 26.03
[DebitAccount] => 2310
[32] => Array
(
[Amount] => 200.00
[DebitAccount] => 2310
If in mysql query use SUM(j.Amount) then get only one total amount (suppose total amount of Column Amount).
With
foreach($data as $result){
if(strlen($result['Amount']) > 0 ) {
echo "Amount ". $result['Amount']. "Account name ". $result['DebitAccount']. "<br>";
print_r (array_sum($result));
}
}
Get something like this
Amount 123.97Account name 2310
2433.97Amount 26.03Account name 2310
2336.03Amount 200.00Account name 2310
Any ideas how to get necessary results (marked bold)?
Update
Changed $query to
$query = "SELECT SUM(j.Amount), j.DebitAccount FROM 18_7_ChartOfAccounts AS c LEFT JOIN 2_1_journal AS j ON (c.AccountNumber = j.DebitAccount) group by j.DebitAccount";
with print_r($data); get array like this
Array
(
[0] => Array
(
[SUM(j.Amount)] =>
[DebitAccount] =>
)
[1] => Array
(
[SUM(j.Amount)] => 110900.16
[DebitAccount] => 2310
)
[2] => Array
(
[SUM(j.Amount)] => 3660.86
[DebitAccount] => 2380
)
With array seems all works. Now with foreach changed to
echo "Amount ". $result['SUM(j.Amount)']. " Account name ". $result['DebitAccount']. "<br>";
Get
Amount 110900.16 Account name 2310
Amount 3660.86 Account name 2380
Amount 85247.40 Account name 2610
Seems also ok. Thanks
You are going about it wrong. You can get the sum through MySql statement itself.
Use the aggrgate function sum along with group by clause.
Like this,
SELECT DebitAccount,sum(Account) from 2_1_journal group by DebitAccount
Your full code:
$query = " SELECT DebitAccount,sum(Account) as Total from 2_1_journal group by DebitAccount";
$sql = $db->prepare($query);
$sql->execute();
$data = $sql->fetchAll(PDO::FETCH_ASSOC);
foreach($data as $result){
if(strlen($result['Total']) > 0 ) {
echo "DebitAccount ". $result['DebitAccount']. "Total is: ". $result['Total']. "<br>";
print_r (array_sum($result));
}
}
SELECT DebitAccount, SUM(Amount)
FROM 2_1_journal
GROUP BY DebitAccount
You have to use the GROUP BY in the query
SELECT DebitAccount, SUM(Amount) AS Amount FROM 2_1_journal GROUP BY DebitAccount

Categories