简体   繁体   中英

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

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

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.

For MySQL, you want to use mysql_real_escape_string . addslashes does almost the same thing and has fewer letters, but apparently it gets some stuff wrong -- don't use it.

For SQL Server, it's a bit more complicated, as (1) MySQL quotes stuff non-standardly, and (2) i don't see a function made to quote stuff for SQL Server. However, the following should work for you...

$escaped_str = str_replace("'", "''", $unsafe_str);

for mysql

USE mysql_real_escape_string

http://php.net/manual/en/function.mysql-real-escape-string.php

like :

// Query
$query = sprintf("SELECT * FROM tblCustomer WHERE user='%s' AND password='%s'",
            mysql_real_escape_string($user),
            mysql_real_escape_string($password));

for mssql

look on the answers here :

How to escape strings in SQL Server using PHP?

You shouldn't really be building the SQL statement dynamically as it's dangerous (and unnecessary). The correct thing to do is to use a paramerised query see http://msdn.microsoft.com/en-us/library/cc296201%28SQL.90%29.aspx

$sql ="SELECT CustomerID FROM tblCustomer WHERE EmailAddress = ? AND Password = ?";
$stmt = sqlsrv_query( $conn, $sql, array($_POST['username'], $_POST['password']));

This is much safer and means you don't have to worry about escaping characters. Another thing is beware of case sensitive / insensitve comparisons. For example if you wanted email address to be case insensitive but password case sensitive use something like:

$sql ="SELECT CustomerID FROM tblCustomer WHERE EmailAddress = ? COLLATE SQL_Latin1_General_CP1_CIAI AND Password = ? COLLATE SQL_Latin1_General_CP1_CSAS";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM