Reputation: 193
The script receives variable from URL:
if(isset($_GET['string'])){
$string = $_GET['string'];
}
Then I use this variable in sql query:
$sql =
"SELECT
*
FROM
mytable
WHERE
mytable.column_a = '".$string."'";
The problem is that this query doesn't execute, where my variable contains special characters. Example:
/myscript.php?string=a>xxx<P>yy@"
Tried to use both htmlentities() and addslashes(). Also tried to copy/paste echo of the variable - works fine.
How can I solve this problem?
Upvotes: 1
Views: 145
Reputation: 906
I suggest that you use urlencode — URL-encodes ion your codes, for more information and details you can also have a look at following link:
http://php.net/manual/en/function.urlencode.php
Upvotes: 0
Reputation: 15997
Please, use parameters instead of concatenate query parts. This code should work fine:
<?php
header('Content-Type: text/html; charset=utf-8');
$serverName = "SERVER\INSTANCE";
$connectionInfo = array("Database"=>"Test");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if(isset($_GET['string'])){
$params = array($_GET['string']);
}
if( $conn === false ) {
echo "Unable to connect.</br>";
die(print_r(sqlsrv_errors(), true));
}
$tsql =
"SELECT *
FROM mytable
WHERE column_a = ?";
$stmt = sqlsrv_query($conn, $tsql, $params);
if( $stmt === false ) {
echo "Error in executing query.</br>";
die(print_r(sqlsrv_errors(), true));
}
while ($obj = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_NUMERIC)) {
echo $obj[0];
}
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
Upvotes: 1
Reputation: 94
Try this query
First check $string is getting correct and then try,
$sql =
"SELECT
*
FROM
mytable
WHERE
mytable.column_a = ".$string;
Upvotes: 0
Reputation: 13969
If column_a is nvarchar datatype try including N before the string quotes.
Upvotes: 0