0

I am using codeigniter to build an app and I am really far in the code.

I have a table with column headers id, page, user and like. Now the problem is, in the mysql query, I realised I cant use the word like for the column name as its a sql keyword I belive.

I can't change the column name from like to something else because it would mean changing 100s of lines of php code.

Is there something that i can do to overcome the clash of the world like?

here is what I mean

$like_variable = 100;
$query =  $this->db->query("SELECT * FROM `table_name` 

            WHERE id ='" . $qry . "' AND 

            page = '" . $_SESSION['p_id'] . "' AND 

            user_id = '" . $_SESSION['user_id'] . "' AND

            like = '" . $like_variable . "'

            ");
            // i think i cant use the world like above but I cant change the column header

Any solutions would be much appreciated thanks in advance

mark
  • 155
  • 3
  • 19
  • 1
    "Like" is a reserved word in SQL. You can use reserved words as column names if you wrap them in back ticks: `\`like\` = 'something'`. You should also use [Prepared Statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead of concatenating your queries. – M. Eriksson Aug 23 '17 at 05:18
  • Thanks :) I have tried 'like' but its not working. Even when I try 'page' it doesnt seem to work with the extra added single quotation marks. any ideas – mark Aug 23 '17 at 05:39
  • It should be _backticks_, not single quotes. Big difference. – M. Eriksson Aug 23 '17 at 05:41
  • Possible duplicate of [When to use single quotes, double quotes, and backticks in MySQL](https://stackoverflow.com/questions/11321491/when-to-use-single-quotes-double-quotes-and-backticks-in-mysql) – M. Eriksson Aug 23 '17 at 05:43
  • Oh wow my bad, thanks a lot ! – mark Aug 23 '17 at 06:00

2 Answers2

3

In SQL, you can use keywords as column names. Wrap them in ``.

SELECT * from `table_name` WHERE `like` = 100
ryantxr
  • 4,119
  • 1
  • 11
  • 25
  • Thanks :) I have tried 'like' but its not working. Even when I try 'page' it doesnt seem to work with the extra added single quotation marks. any ideas – mark Aug 23 '17 at 05:39
2

Change like to:

`like`

Result:

$like_variable = 100;
$query =  $this->db->query("SELECT * FROM `table_name` 

        WHERE id ='" . $qry . "' AND 

        page = '" . $_SESSION['p_id'] . "' AND 

        user_id = '" . $_SESSION['user_id'] . "' AND

        `like` = '" . $like_variable . "'

        ");
M. Eriksson
  • 13,450
  • 4
  • 29
  • 40