Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add parameters to a PHP mssql query

Tags:

php

sql-server

Given the following query (in the code, NOT a stored procedure); how can I add parameters to the query rather than including the condition values directly in the query? In other words: how can I make this database call secure?


$dbhandle = mssql_connect($myServer, $myUser, $myPass); 
$selected = mssql_select_db($myDB, $dbhandle); 

$query  = "SELECT lastname, firstname, address, phone, email ";
$query .= "  FROM person";
$query .= " WHERE lastname LIKE '" . $lastName . "'";

$result = mssql_query($query);

while($row = mssql_fetch_array($result)) {
... etc.
like image 801
KBoek Avatar asked Jan 18 '26 20:01

KBoek


2 Answers

Use PDO to make it secure

http://php.net/manual/en/book.pdo.php

like image 113
Adam Hopkinson Avatar answered Jan 21 '26 10:01

Adam Hopkinson


First of all abandon the outdated extension and use sqlsrv instead:

These functions allow you to access MS SQL Server database.

This extension is not available anymore on Windows with PHP 5.3 or later.

SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

After that you get suppport for prepared statements:

$dbh = sqlsrv_connect ($serverName, $credentials);
$stmt = sqlsrv_prepare($dbh, 'SELECT lastname,firstname,address,phone,email FROM person WHERE lastname LIKE ?', array(&$lastName));


if(sqlsrv_execute($stmt))
{
   while(false !== ($row = sqlsrv_fetch_array($stmt)){
     // do stuff with $row
   }
}

Of course if i were i would just use PDO as others have suggested with presents the same interface to all db the extensions it supports.

If youre stuck using mssql for some reason then i believe youre also stuck manually escaping all your query parameters.

like image 30
prodigitalson Avatar answered Jan 21 '26 10:01

prodigitalson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!