Search code examples
sqlcodeigniteractiverecordpyrocms

Active record query failed - Escape quote from query


Background

  • Framework: Codeignighter/PyroCMS

I have a DB that stores a list of products, I have a duplicate function in my application that first looks for the common product name so it can add a 'suffix' value to the duplicated product.

Code in my Products model class

$product = $this->get($id);

$count = $this->db->like('name', $product->name)->get('products')->num_rows();

$new_product->name = $product->name . ' - ' . $count;

On the second line the application fails only when the $product->name contains quotes. I was with the understanding that Codeignighter escaped all strings so I dont know why I get this error.

So I tried to use MySQL escape string function but that didn't help either.

The Error Message

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Book%'' at line 3

SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'

var_dump

Below is the output of doing a var_dump on product->name before and after the line in question;

string 'Harry's Book' (length=12)

A Database Error Occurred

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 's Book%'' at line 3

SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'

Solution

  • Let's do some testing about this.

    Here is what you are doing

    $count = $this->db->like('name', $product->name)->get('products')->num_rows();
    

    And i suspect $product->name contains this.

    Harry's Book

    As we know this is coming from the database table as you are using. Where you are using the upper query mentioned it is wrapping it with single quotes and producing this result.

    SELECT * FROM `products` WHERE `name` LIKE '%Harry\\'s Book%'
    

    As you see it is escaping apostrophy to tell it is not end of string Therefore escaping it with two slashes.One for apostrophy and one for being in single quote.

    What you have to do is Before assigning the parameter to query wrap it with double quotes.

    $product_name   =   "$product->name";
    

    And now pass it to query.

    $count = $this->db->like('name', $product_name)->get('products')->num_rows();
    

    The output will be this

    SELECT * FROM `products` WHERE `name` LIKE '%Harry\'s Book%'
    

    You see the differece here. It contains single slash now and the record will be found.