Search code examples
phpsql-serverpdotruncate

How to turn off ANSI_WARNINGS using PDO in PHP


My Question

How can I turn off ANSI_WARNINGS in SQL Server using PDO in PHP?

My Justification

Unless my visitors are using modern browsers with support for HTML 5, I cannot set a max length to textareas, which means my query returns an error when the data within the text box is too large. Resultantly, I need to turn off ANSI_WARNINGS to force SQL Server to truncate any text that is too large to insert into the field on the database...

What I have tried...

I have tried running the following query:

$this->mssql->sql("SET ANSI_WARNINGS = OFF");

and then my insert query immediately afterwards:

$this->mssql->sql("INSERT INTO...");

Ignore the $this->mssql->sql part, this simply calls my own wrapper class for PDO


Solution

  • Try

    SET ANSI_WARNINGS OFF;
    

    Without = sign

    ADDITIONAL INFORMATION

    If you want to turn off ARITHABORT (i.e. do not raise errors when encountering divide-by-zero) and your database's compatibility level is 80 or lower, setting just ANSI_WARNINGS OFF is not sufficient. You need to SET ARITHABORT OFF as well. However, note that Microsoft warns about turning this off.

    Test

    SET ARITHABORT OFF;
    GO
    SET ANSI_WARNINGS OFF;
    GO
    
    SELECT 1/0      --<-- Returns NULL instead of arithmetic overflow error.
    GO
    
    DECLARE @TABLE TABLE (VAL VARCHAR(2))
    INSERT INTO @TABLE VALUES ('Long String')   --<-- inserts data and truncates extra bits
    
    SELECT * FROM @TABLE
    
    GO