-1
$raw_results = mysql_query("SELECT sno,name,email,phone,smpc FROM existing_sales_details
    WHERE (`sno` LIKE '%".$query."%') OR(`name` LIKE '%".$query."%') OR (`email` LIKE '%".$query."%') OR  (`phone` LIKE '%".$query."%') OR (`smpc` LIKE '%".$query."%')
    UNION 
    SELECT sno,name,email,phone,smpc FROM sale_details
    WHERE (`sno` LIKE '%".$query."%') OR(`name` LIKE '%".$query."%') OR (`email` LIKE '%".$query."%') OR  (`phone` LIKE '%".$query."%') OR (`smpc` LIKE '%".$query."%')
    UNION
    SELECT sno,name,email,phone,smpc FROM uncharge
    WHERE (`sno` LIKE '%".$query."%') OR(`name` LIKE '%".$query."%') OR (`email` LIKE '%".$query."%') OR  (`phone` LIKE '%".$query."%') OR (`smpc` LIKE '%".$query."%')")
    or die(mysql_error());

i have three tables and when i retrieve data from them i also want to get the table name to know this data belongs to to this table how can i retrieve the table names according to data please suggest me.

lxe
  • 7,051
  • 2
  • 20
  • 32
prem
  • 5
  • 5
  • 1
    Stop using the `mysql_*` functions. They have been deprecated since v5.5 (Jun 2013) and removed since v7.0 (Dec 2015). Instead use the [**mysqli_***](https://secure.php.net/manual/en/book.mysqli.php) or [**PDO**](https://secure.php.net/manual/en/book.pdo.php) functions with [**prepared statements**](https://secure.php.net/manual/en/pdo.prepare.php) and [**bound parameters**](https://secure.php.net/manual/en/pdostatement.bindparam.php). – Alex Howansky Apr 21 '17 at 19:15
  • What do you mean?! The table name(s) should be known before executing the query?!!! – SaidbakR Apr 21 '17 at 19:18
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)***. Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Apr 21 '17 at 19:34

2 Answers2

2

What you can easily do is:

SELECT colum1, column2, 'tableName1' as tableName FROM tableName1
UNION
SELECT colum1, column2, 'tableName2' as tableName FROM tableName2

You can always add a string or number as a column in your select. It will be the same for each row.

Viliam Aboši
  • 447
  • 2
  • 14
0

Besides the issues with the old mysql libraries it's actually fairly easy to return the table name.

Since you are using UNION and essentially 3 selects all you have to do is to the end of each select Change

 SELECT sno,name,email,phone,smpc

To

 SELECT sno,name,email,phone,smpc,'XXXX' AS tablename

And replace XXXX as the table name in each query

Forbs
  • 1,256
  • 1
  • 7
  • 9