Search code examples
sql-serverphptransactionsfreetds

PHP PDO - The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION


While inserting into MSSQL using PHP PDO Dblib I am having this error

exit signal Segmentation fault in apache error log

When I checked the free tds log the error is

The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION

However this is happening for a particular case only that is when I have string for a float data type. Below is my code:

$conn = new PDO('dblib:host=hostname;dbname=mydbname', 'user', 'password');
$conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$conn->beginTransaction();
$query = 'INSERT INTO [TestTable] ([RecordNo], [Paymode], [VATVALUE])
          VALUES (:RecordNo, :Paymode, :VATVALUE)';
$stmt = $conn->prepare($query);
try {
    $stmt->execute( [":VATVALUE" => "158.4'", ":Paymode" => "CREDIT", 
                                    ":RecordNo" => "ABC-312735"] );
    $conn->commit();
} catch(PDOException $e) {
    $conn->rollback();
}

Please note the vat value which I have set it as

158.4'

for replicating the error. However when I remove the transaction statements then it is throwing the proper error i.e.

Error converting data type varchar to float

Interestingly the beginTransaction() is working perfectly if I specify a wrong column name in the statement. The transaction is not working only for this conversion error and throwing signal segmentation fault error.

I am using PHP 7.0 in ubuntu 16.04. Wondering why rollback working fine in all cases like wrong column names or table name but not in the conversion case.


Solution

  • There are errors in SQL Server which will automatically roll back your transaction, and it's an error to attempt a rollback after that. Instead of

    $conn->rollback();
    

    try executing the batch

    if @@trancount>0 rollback;
    

    I don't know PHP but perhaps something like:

    $conn->prepare("if @@trancount>0 rollback;")->execute();