-1

I have a query which in Psuedo MYSQL says:

"SELECT * FROM table WHERE col1 = $x OR col2 = $x"

Now I am iterating through each line of the results but want to determine for each one which column x is in. Therefore I want to be able to return column_name where the variable $x == $x in the table.

I have tried using fetch_field() but to no avail.

GMB
  • 216,147
  • 25
  • 84
  • 135

1 Answers1

0

You can use a case expression to add one more column to the resultset that indicates from which column the searched value comes from

SELECT 
    t.*,
    case when col1 = :x then 'col1' else 'col2' end which_col
FROM table t
WHERE :x IN (col1, col2)

Side notes:

  • you do want to use parameterized queries for efficiency and safety - more about that here

  • you should take the habit to enumerate the columns that you want in the select clause rather than using blindly select * - this makes the query easier to understand and maintain, and can make your code more efficient

  • you can use then IN to shorten the condition in the WHERE clause a little

GMB
  • 216,147
  • 25
  • 84
  • 135