We're a community of 1.1M IT Pros here for help, advice, solutions, professional growth and fun. Join us!
1,080,464 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Start New Discussion Reply to this Discussion

mysql select query with join not showing the results of multiple rows

I am trying to create a search form for my database where a user can search for a customer name and all of that customers addresses will be displayed. my structure looks like this

Customer table

  • ID
  • First Name
  • Last name
  • Company Name

Address Table

  • ID
  • line 1
  • post code
  • town
  • Customer_ID

Site Table

  • ID
  • Address_ID
  • notes

I take either the first, last, or company name as an input($field) and store this as a variable along with which column they want to search in($query) then I use the following query to check the database for matching criteria

$data = mysql_query("SELECT *
     FROM customer 
     INNER JOIN address ON customer.ID = address.customer_ID
     INNER JOIN sites ON address.ID = sites.address_ID 
     WHERE customer.ID IN (SELECT customer.ID 
     FROM customer
     INNER JOIN address ON customer.ID = address.customer_ID 
     INNER JOIN sites ON address.ID = sites.address_ID
     WHERE upper(customer.$field) LIKE'%$query%')") ;

I print the results using

    while($results = mysql_fetch_array($data)){
            echo "<br>"; 
            echo $results['First_Name']; 
            echo " "; 
            echo $results['Surname']; 
            echo $results['town']; 
            echo " "; 
            echo $results['postcode'];

The problem occurs when one customer has multiple addresses. A home address and a site address that are different. The query will only print one of the addresses, the site address ( which is submitted second and seems to overwrite the home address)

in the address table both of these addresses contain the same Customer_ID, how can I get them to both be displayed rather than just one?

2
Contributors
1
Reply
1 Day
Discussion Span
10 Months Ago
Last Updated
2
Views
Ebiso
Newbie Poster
3 posts since Jun 2012
Reputation Points: 0
Solved Threads: 0
Skill Endorsements: 0

Your second clause is redundant.
In effect your query reads:

select * from customers where id in (...)

This can select at most one customer per id.

Instead use:

SELECT *
FROM customer 
INNER JOIN address ON customer.ID = address.customer_ID
INNER JOIN sites ON address.ID = sites.address_ID 
WHERE upper(customer.$field) LIKE'%$query%'
smantscheff
Nearly a Posting Virtuoso
1,297 posts since Oct 2010
Reputation Points: 321
Solved Threads: 270
Skill Endorsements: 8

This article has been dead for over three months: Start a new discussion instead

Post: Markdown Syntax: Formatting Help
 
You
View similar articles that have also been tagged:
 
© 2013 DaniWeb® LLC
Page generated in 0.0679 seconds using 2.68MB