1

I would like to run several SQL Server queries in php but he does not want to accept that with me. Here is my php script:

<?php
      error_reporting(0);

      $serverName = "SERVERNAME";
      $connectionInfo = array( "UID"=>"Username", "PWD"=>"password", "Database"=>"databasename", "MultipleActiveResultSets"=>true);

      $conn = sqlsrv_connect( $serverName, $connectionInfo);

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

     $sql = "INSERT INTO TABLE (column) VALUES (?)";
     $tsql = "INSERT INTO TABLE_NEW(column, column, column) Values (?, 'INSERT', 'WEBSERVER')";
     $params = array($_POST["addSomething"]);

       $stmt = sqlsrv_query( $conn, $sql, $params, $tsql, $params);
       if( $stmt == false ) {
         die(print_r( sqlsrv_errors(), true));
       }
       else
       {
           echo '<script language="javascript">';
           echo 'alert(Alert what Happend!)';  //not showing an alert box.
           echo '</script>';
       }
       sqlsrv_close($conn);
       ?>

I took out the private data and replaced it with random names. I am happy about any help.

1
  • Did you mean to add the second query to the first (perhaps with $sql .= with the .) because at the moment it overwrites it. Commented Mar 1, 2019 at 7:35

1 Answer 1

2

You can not pass more than one statement to sqlsrv_query(). In your case you have two options:

  • Generate one complex T-SQL statement. In this case, the number of placeholders must match the number of passed parameters.
  • Execute each statement separately

Complex statement:

<?php
...
$sql = "
    INSERT INTO TABLE (column) VALUES (?); 
    INSERT INTO TABLE_NEW(column, column, column) Values (?, 'INSERT', 'WEBSERVER')
";
$params = array(
    $_POST["addSomething"],
    $_POST["addSomething"]
);
$stmt = sqlsrv_query($conn, $sql, $params);
if ($stmt === false ) {
   # Your code here
} else {
   # Your code here
}
...
?>

Notes:

PHP Driver for SQL Server supports multiple result sets. If you use one complex statement and one or more of your statements are SELECT statements, you need to call sqlsrv_next_result() to make active the next result (first result is active by default).

Sign up to request clarification or add additional context in comments.

5 Comments

Which one i should pick now Zhorov?
@Philipp. Try with first one.
Tanks a Lot @Zhorov the first one Works :-) Can you delete the second so others may don't be confused.
@Philipp. I've updated the answer and question's tags (sqlsrv is added).
@Zharov Thanks a lot! Have a nice Day!

Your Answer

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