Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you escape quotes in a sql query using php?

Tags:

php

sql-server

I have a query

$sql ="SELECT CustomerID FROM tblCustomer 
WHERE EmailAddress = '".addslashes($_POST['username']) ."' AND Password = '".addslashes($_POST['password']) ."'";

//  while printing,   it will be

SELECT CustomerID FROM tblCustomer WHERE EmailAddress = 'test@ab\'c.com' AND Password = '123'

if we executing this in a mysql server it works, but not in a sql server

what is the solution for this? . Iam using sql server

like image 210
Linto P D Avatar asked Jul 15 '10 05:07

Linto P D


1 Answers

addslashes() will escape single quotes with a leading backslash which is valid syntax in MySQL but not in MS SQL Server. The correct way to escape a single quote in MS SQL Server is with another single quote. Use mysql_real_escape_string() for MySQL (mysql_escape_string() has been deprecated). Unfortunately, no analogous mssql_ function exists so you'll have to roll your own using str_replace(), preg_replace() or something similar. Better yet, use a database neutral abstraction layer such as PDO that supports parameterized queries.

like image 74
Asaph Avatar answered Sep 27 '22 22:09

Asaph