Updating MSSQL table with PHP + sqlsrv

danzo picture danzo · Apr 18, 2015 · Viewed 14.9k times · Source

I'm trying to do the simplest thing...

I have a form with 2 fields. I want to enter data in those fields and have them write that data to my db (mssql using sqlsrv driver).

Connecting to the db isn't a problem. Here's my form processor (only set up to update quantity (qnty) at the moment):

require_once 'dbconnect.php';

$partno = $_POST["partno"];
$qnty = $_POST["qnty"];

$sql = 'UPDATE WestDevDB SET LocationQty = $_POST["qnty"]';

$result = sqlsrv_query($conn,$sql) or die(sqlsrv_errors());

All I get is the error:

Notice: Array to string conversion in filepath\file.php on line 8 Array

and nothing writes.

I've tried changeing $_POST["qnty"] to $_POST["qnty"][0] thinking that would solve the issue, but it makes no difference.

Any thoughts on this?

Answer

Marc B picture Marc B · Apr 20, 2015

Basic PHP Syntax 101: '-quoted strings do NOT interpolate variables. That means your query definition:

$sql = 'UPDATE WestDevDB SET LocationQty = $_POST["qnty"]';

is sending the literal characters $, _, P etc... as the value to compare LocationQty against. That also means that your query is causing a syntax error, because $_ etc... is not a valid field name, in pretty much any database under the sun.

And even if '-quoted strings DID interpolate variables:

a) you'd be wide open for sql injection attacks anyways.
b) Array keys cannot be quoted inside strings, unless you using the {} syntax:

$sql = "UPDATE ... = {$_POST['qnty']};"
or
$sql = "UPDATE ... = " . $_POST['qnty'];