1

I was working with a database in MySQL, where I have a table say ABC.

I want to query the database for a given search keyword, and display the output in a table. When I am querying with the following code, it is working fine:(Games Played 1 is a column name)

if($_POST['searchby'] == "Games Type"){
          $query_Recordset1 = "SELECT * FROM users_entity WHERE `Games Played 1' LIKE '%".$searchword."%'";

However, when I am trying to check whether the keyword is present in two columns, Games Played 1 or Games Played 2, it is not working. I am using the following code for that.

if($_POST['searchby'] == "Games Type"){
          $query_Recordset1 = "SELECT * FROM elgg_users_entity WHERE `Games Played 1` OR `Games Played 2` LIKE '%".$searchword."%'";

Can anyone suggest where I am doing wrong?? Also, when I run the webpage with the above code, it gives a warning as "The MySQL server has gone away"

Arnab
  • 483
  • 1
  • 6
  • 14
  • 2
    You are missing the first condition: `Select * from table WHERE condition OR condition`. You have to use `'Games Played 1' LIKE 'SOMETHING' OR 'Games Played 2' LIKE 'SOMETHING'`. Run the final generated query outside php and see. – FirstOne Dec 27 '15 at 16:50
  • Thanks all, it is working fine now.. – Arnab Dec 27 '15 at 16:55
  • 1
    Also, it looks like you are vulnerable to SQL Injection. Take a look at [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php). – FirstOne Dec 27 '15 at 16:56

3 Answers3

3
if($_POST['searchby'] == "Games Type"){
          $query_Recordset1 = "SELECT * FROM elgg_users_entity WHERE `Games Played 1` LIKE '%".$searchword."%' OR `Games Played 2` LIKE '%".$searchword."%'";
Vojko
  • 604
  • 3
  • 12
2

Your query should be like this:

$query_Recordset1 = "SELECT * FROM elgg_users_entity WHERE `Games Played 1` LIKE '%".$searchword."%' OR `Games Played 2` LIKE '%".$searchword."%'";
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
2

Errors

  1. Wrong WHERE condition.

So final code is

if($_POST['searchby'] == "Games Type"){
      $query_Recordset1 = "
      SELECT * 
      FROM elgg_users_entity 
      WHERE table_coumn1 
        LIKE '%$searchword%'  
      OR table_coumn2 
        LIKE '%$searchword%' ";

For Your Information

Don't use spaces between table column names(Games Played 1). Add it with _separated word. (Games_Played_1).

Hence make it all small caps as best practices

Abdulla Nilam
  • 36,589
  • 17
  • 64
  • 85