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']; 
}
2
  • 1
    Show us what you tried that isn't working Commented Dec 16, 2013 at 13:58
  • 1
    or don't bother and just sit back and let us do it all for you Commented Dec 16, 2013 at 14:13

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.