note 117807 added to function.sqlsrv-prepare

From: Date: Wed, 12 Aug 2015 20:54:05 +0000
Subject: note 117807 added to function.sqlsrv-prepare
Groups: php.notes 
Request: Send a blank email to php-notes+get-203324@lists.php.net to get a copy of this message
Be careful with your variables once you bind them to a statement with sqlsrv_prepare. Consider the following: <?php $dude = ''; $time = new DateTime(); $sql = "INSERT INTO my_table (person, timein) VALUES (?, ?)"; $stmt = sqlsrv_prepare($conn, $sql, array(&$dude, &$time)); ... // many lines later foreach ($times as &$time) { //do stuff } // later still... $time = $times['start']; if( sqlsrv_execute( $stmt ) === false ) { die( print_r( sqlsrv_errors(), true)); } ?> I did something like this. I prepared a statement at the start, used the variable again in the middle, and then set the value I wanted before running the query. Trouble is, I used the variable as an iterator instead of a simple scalar. This caused PHP to use a different location in memory, and the location it was previously bound to was invalid. So SQL simply inserted a default date/time. Worse, because SQL just inserted a default, it didn't throw any errors, and in trying to debug it, I did something like this: <?php var_dump($time); sqlsrv_execute($stmt); $q = "SELECT * FROM my_table WHERE id=@@IDENTITY"; $r = sqlsrv_query($conn, $q); $row = sqlsrv_fetch_array($r); $id = $row[0]; var_dump($row['time']); ?> Having it appear as though you're sending SQL the correct data, and seeing it spitting back something else entirely is absolutely maddening. So if SQL seems to be inserting garbage with prepared statements, MAKE SURE YOU'RE NOT USING THE VARIABLES ANYWHERE ELSE. ---- Server IP: 72.52.91.14 Probable Submitter: 96.233.109.34 ---- Manual Page -- http://php.net/manual/en/function.sqlsrv-prepare.php Edit -- https://master.php.net/note/edit/117807 Del: integrated -- https://master.php.net/note/delete/117807/integrated Del: useless -- https://master.php.net/note/delete/117807/useless Del: bad code -- https://master.php.net/note/delete/117807/bad+code Del: spam -- https://master.php.net/note/delete/117807/spam Del: non-english -- https://master.php.net/note/delete/117807/non-english Del: in docs -- https://master.php.net/note/delete/117807/in+docs Del: other reasons-- https://master.php.net/note/delete/117807 Reject -- https://master.php.net/note/reject/117807 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#203324) next »