I have two Tables:
Table-1: notes

Table-2: contacts

My basic objective is to perform following query:
list * from contacts where (search text exists in contacts) or (search text exists in notes for that contact)
I have written following code to do this:
<?php
require_once('config.php');
$nwhere = "WHERE note_text LIKE '%".addslashes($_GET['s'])."%' ";
$cwhere = "contact_text LIKE '%".addslashes($_GET['s'])."%' ";
$result = mysql_query("SELECT * FROM contacts INNER JOIN notes ON contact_id = note_contact $nwhere OR $cwhere ORDER BY contact_id");
while($row = mysql_fetch_array($result))
{
echo $row['contact_id'];
echo '<br/>';
}
?>
When Search Text is azeem, the above code prints only 4001, however output should be:
4000
4001
Also I dont want to repeat contact_id in Output.
Please suggest.
Code After correction by Fluffeh:
$where_clause = " where contacts.contact_text like '%".addslashes($_GET['s'])."%' or notes.note_text like '%".addslashes($_GET['s'])."%'";
$result = mysql_query("select notes.note_id, notes.note_contact, contacts.contact_id, contacts.contact_text, notes.note_text from contacts left outer join notes on contacts.contact_id=notes.note_contact $where_clause");
while($row = mysql_fetch_array($result))
{
echo $row['contact_id'];
echo '<br/>';
}
?>
This code picks up correct rows from tables but there is one minor issue that it repeats the output (contact_id). For example it showed following output when i gave search parameter nawaz:
4001
4001
4001
4001
4001
4002
4003
Thanks for your help, please help me out to fix this.
If you don’t want a column repeated, you can’t use
SELECT * FROMbut rather you will need to use the column names you want to select.You aren’t getting the 4000 result you are expecting because you are doing an inner join on a field that doesn’t exist in the other table. (Azeem = 4000, but no note_contact exists for user 4000).
You should consider switching to an outer join instead. Maybe something like this:
Edit: Seems we were both still working – I gave made a sqlFiddle which has the basic schema and a working outer join for the example.
My create schema is:
outer Join Query:
Code working from Nida: