I think this is a classical SQL problem but I was not able to find any hint on the internet.
My database tables are:
Table User:
ID UserName Adress
1 Uwe No 1
2 user2 No 2
3 name3 No 3
Table Tel:
ID telNumber user_id
1 123 1
2 234 1
3 123 2
4 567 1
5 900 3
6 800 3
7 111 1
With this select:
SELECT user.UserName, tel.telNumber, user.Adress
FROM [user] INNER JOIN tel ON user.ID = tel.user_id;
I will get:
UserName Tel Adress
---------------------------
Uwe 123 No 1
Uwe 234 No 1
user2 123 No 2
Uwe 567 No 1
name3 900 No 3
name3 800 No 3
Uwe 111 No 1
----------------------------
What I'am looking for is something like this now:
Name: Uwe
Tel1: 123
Tel2: 234
Tel3: 567
Tel4: 111
Adress: No 1
Name: name3
Tel1: 900
Tel2: 800
Adress: No 3
How can I get this result? How I have to adapt my SQL statement, that I get a comfortable way to catch it by PHP?
You can use the group_concat
with group by
to get each user with their phone numbers. You then could use explode, or some other function to split out the phone numbers and iterate over them. Example:
SELECT u.UserName, group_concat(t.telNumber) as numbers, u.Adress
FROM user as u
INNER JOIN tel as t
ON u.ID = t.user_id
group by u.ID
SQL Demo: http://sqlfiddle.com/#!9/6dca9b/3
PHP implementation would be something like:
<?php
$numers = array('User1' => '1', 'User2' => '123,456');
foreach($numers as $user => $num){
echo $user . PHP_EOL;
if(strpos($num, ',') === FALSE) {
echo 'Tel1:' . $num .PHP_EOL;
} else {
$nums = explode(',', $num);
foreach($nums as $key => $temp){
echo 'Tel' . ($key + 1) . ':' . $temp .PHP_EOL;
}
}
}
Demo: https://3v4l.org/OE3IA
As a rule of thumb: don't mix presentation data with logic.
You don't in fact need an SQL query to return the sequence number for a common-theme list of records. This detail is best left to the application layer, i.e. your PHP code. Let your PHP code "know" when it's listing telephone numbers for a given user (which should be trivial) and present them in an enumerated fashion like you've shown (pseudo code):
for each user:
i = 0
for each 'user' phone number:
i++
show phone number (i)
next
next
It is (generally) less important to know which telephone is in which position than knowing you've got them all right for a user.