Ikhlak S.
Ikhlak S.

Reputation: 9034

MySQL and PHP escape back slash

I have an constant that is a string that contains a back slash \.

The problem is, MySQL seems to escape this character which is not the behavior expected.

Here is the code:

const METHOD_TYPE_CREDITCARD = "Braintree\CreditCard";

$sql = "SELECT transaction_id AS id,  
  CASE
    WHEN source_type = '0' THEN '".PaymentGateway::METHOD_TYPE_CREDITCARD."'
  END AS source 
FROM transactions WHERE invoice_id = :id"

It sure runs the query properly but escapes the \. So the output looks like:

[id] => myx0kpe8
[source] => BraintreeCreditCard

I tried what @strawberry mentioned. Still the same results with

const METHOD_TYPE_CREDITCARD = "Braintree\\CreditCard";

Upvotes: 2

Views: 1843

Answers (1)

Christian Gollhardt
Christian Gollhardt

Reputation: 17004

What you have done, is a self made SQL Injection.

As already commented, you should use parameters in form of prepared statements (PDO or the equvivalent in mysqli) instead of string concatenation.

$stmt = $dbh->prepare("SELECT transaction_id AS id,  
  CASE
    WHEN source_type = '0' THEN ':creditcard'
  END AS source 
FROM transactions WHERE invoice_id = :id");
$stmt->bindParam(':creditcard', PaymentGateway::METHOD_TYPE_CREDITCARD);

You should always use parameters because of security. It is insane to not use it in these days, because of Sql Injection.

Upvotes: 4

Related Questions