Php calling sqlserver backup database script, backup file created and then deleted

前端 未结 1 1589
情书的邮戳
情书的邮戳 2021-01-06 07:36

I have a php calling sqlserver backup script. The script, if executed directly from SSMS, it created the backups successfully. But, when called via php, I can see the file c

相关标签:
1条回答
  • 2021-01-06 08:35

    Here is a solution, that works for me:

    • execute sqlsrv_configure("WarningsReturnAsErrors", 0); to change the settings for error handling.
    • remove WITH STATS = 1 from BACKUP DATABASE statement.

    I'm able to reproduce this issue with a test case using Apache 2.4, PHP 7.1.12 and Microsoft PHP Driver for SQL Server (php_sqlsrv_71_ts_x86.dll, version 4.3). The only difference is that the example uses SQLSRV Driver (I can't use PDO_SQLSRV Driver in my testing environment).

    PHP

    <?php
        sqlsrv_configure("WarningsReturnAsErrors", 0);
    
        // Connection
        $serverName = "127.0.0.1\instance,1433";
        $connectionInfo = array(
            "UID"=>"user",
            "PWD"=>"password",
            "Database"=>"ProdDB"
        );
        $conn = sqlsrv_connect($serverName, $connectionInfo);
        if ($conn === false) {
            echo "Unable to connect.</br>";
            die(var_export(sqlsrv_errors(), true));
        }
    
        // Backup database
        $strSQL = file_get_contents("archdata.sql");
        if (!empty($strSQL)) {
            $query = sqlsrv_query($conn, $strSQL);
            if ($query === false) {
                die(var_export(sqlsrv_errors(), true));
            } else {
                sleep(5);  
                echo "Success";
            }
        }   
    ?>
    

    T-SQL (archdata.sql)

    declare 
        @path varchar(100),
        @fileDate varchar(20),
        @fileName varchar(140)
    
    SET @path = 'd:\Backup\'   
    SELECT @fileDate = CONVERT(VARCHAR(20), GETDATE(), 112)  
    SET @fileName = @path + 'ProdDB_' + @fileDate + '.BAK' 
    BACKUP DATABASE ProdDB TO DISK=@fileName
    

    Don't forget to give necessary rights to 'D:\Backup' folder.

    0 讨论(0)
提交回复
热议问题