0

I have two tables:

Table 1

  • contacts
    • id
    • email
    • name
    • lastname
    • postcode
    • straat
    • huisnr
    • woonplaats
    • klantnummer
    • bsn
    • land
    • debiteurnummer

Table 2

  • contacts_group
    • id
    • mail
    • group_name

How can I select and order this 2 tables in one query. I've tried union and left join, but did not work.

$result = mysqli_query($database->connection,
    "SELECT * 
     FROM contacts 
     WHERE owner = '$session->username'
     ORDER BY name ASC ,bedrijfsnaam ASC") 
or die(mysqli_error());

while($roww = mysqli_fetch_array($result)){
    echo $roww['email'];
    echo $roww['name']; 
}

Table contacts_group:

$result = mysqli_query($database->connection,
    "SELECT * 
     FROM contacts_group 
     WHERE owner = '$session->username'
     ORDER BY group_name ASC") 
or die(mysqli_error());

while($roww = mysqli_fetch_array($result)){
   echo $roww['mail'];
   echo $roww['group_name']; 
}
richsage
  • 26,912
  • 8
  • 58
  • 65
Yunus
  • 7
  • 1

2 Answers2

1

Escape your variables. You should not put the php variable unescaped in sql query. You can suffer from sql injections.

If you want to join two tables by foregin key you can do:

SELECT * FROM contacts, JOIN contacts_group ON contacts_group.id = contacts.group_id 
WHERE contacts.owner = '$session->username' ORDER BY contacts.name

But you are missing group_id in contacts table or some foregin key to connect two tables.

gorgi93
  • 2,457
  • 8
  • 30
  • 53
0

Before do it read this topic, after try to use mysql join construction

Community
  • 1
  • 1
RDK
  • 4,540
  • 2
  • 20
  • 29