Prepared params LIKE statement Not working with SQ

2020-04-21 06:27发布

问题:

I am using SQLSRV 3.0 for PHP and working against a MSSQL2008.

My problem I am having, is that I can't get a LIKE statement in the query to work?

$connectionOptions = array( "Database"=>$myDB, "UID"=>$myUser, "PWD"=>$myPass);
$conn = sqlsrv_connect( $myServer, $connectionOptions);

$params = array(
    "$sID%",
    "$sUser%"
);
$sql = "select * from tbl where col2 LIKE ? or col2 LIKE ?";

$stmt = sqlsrv_query($conn, $sql, $params); 

if( $stmt === false) {
    die( print_r( sqlsrv_errors(), true) );
}

The problem is related to the design of the items in the params array, any suggestion?

Regards, Jakim

回答1:

Adjust your code to the following:

$sql = "select * from tbl where col2 LIKE ? or col2 LIKE ?";
$params = array($sID."%", $sUser."%");
$stmt = sqlsrv_query( $conn, $sql, $params);


回答2:

Try to do this:

$strSQL = "SELECT * FROM tbl WHERE col2 like '%' + CONVERT(NVARCHAR, ?) + '%' or col2 like '%' + CONVERT(NVARCHAR, ?) + '%' ";

$searchTerm = "<<some multibye characters>>";

$searchTerm = iconv('utf-8', 'utf-16le', $searchTerm);

$params = array( array($searchTerm, NULL, SQLSRV_PHPTYPE_STRING(SQLSRV_ENC_BINARY)));