1

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?

4
  • 1
    Use query parameters instead of stuffing the value into the query string. Commented Aug 29, 2016 at 10:57
  • I would also suggest the same thing, use query parameters instead of putting the values in your php query string Commented Aug 29, 2016 at 11:00
  • If you have special characters and you take the string from URL, dont you need to use decoding? php.net/manual/en/function.htmlspecialchars-decode.php Commented Aug 29, 2016 at 11:00
  • either you use parameters which will fix it for you, or you write a few pages of code to escape every special character. Commented Aug 29, 2016 at 11:01

4 Answers 4

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

If column_a is nvarchar datatype try including N before the string quotes.

Comments

0

Try this query

First check $string is getting correct and then try,

$sql = 
"SELECT 
    *
FROM 
    mytable
WHERE
    mytable.column_a = ".$string;

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.