0

I have two tables One is registration and the other is user table: I want to search records from both the tables, i can search the record from one table by the step given below but did not know at the same time some text fiels are there in my form which should match with the records in the database i.e. name and address are comming from the other tables.

<?

  $gender=$_POST['GENDER'];
  $age=$_POST['AGE'];
  $Religion=$_POST['RELIGION'];

  $name=$_POST['NAME'];
  $address=$_POST['ADDRESS'];

 $sql = mysql_query("select * from registration where `religion` LIKE '%".$Religion."%' AND `age` LIKE '%".$age."%' AND `gender` LIKE '%".$gender."%'") or die(mysql_error());

  while($row=mysql_fetch_array($sql)){
 ---
 --
 }

My Table Description is as follows:

Registration Table:
Userid
Gender
Age
Religion

User Table:
uid
name
address
user3026519
  • 543
  • 7
  • 17
  • 36
  • Your SQL is in a potentially dangerous form, it is vulnerable to SQL injection, you might want to read this question: http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – paul Apr 17 '14 at 16:52
  • Thanks.. for your suggestion can you let me know how can i solve my above problem, i have various dropdowns and textboxes and want to show records which matches from both the tables because some records will be searched from user table and some from registration. – user3026519 Apr 17 '14 at 16:54

1 Answers1

0

Try using UNION -

$sql = "(SELECT * FROM registration WHERE 
         `religion` LIKE '%".$Religion."%' AND
         `age` LIKE '%".$age."%' AND 
         `gender` LIKE '%".$gender."%')  UNION

        (SELECT * FROM user WHERE 
         `name` LIKE '%".$name."%' AND 
         `address` LIKE '%".$address."%')";

ADVICE: Avoid using mysql_* functions since it is deprecated. Learn mysqli or PDO

Parag Tyagi
  • 8,780
  • 3
  • 42
  • 47
  • Thanks.. I have tried the following query but it is not returning any row : $sql = mysql_query("(select * from registration where `religion` LIKE '%".$Religion."%' AND `gender` LIKE '%".$genders."%' AND `Age` LIKE '%".$age."%') UNION (SELECT * FROM user WHERE `name` LIKE '%".$name."%')"); – user3026519 Apr 17 '14 at 17:16
  • Is there any problem in syntax. – user3026519 Apr 17 '14 at 17:16
  • I don't think so. Syntax seems fine. Your solution is `UNION` – Parag Tyagi Apr 17 '14 at 17:20
  • No records are being searched and displayed,even though i am selecting those records which are in database. – user3026519 Apr 17 '14 at 17:53