Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
619 views
in Technique[技术] by (71.8m points)

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

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 created on the destination folder, but it seems that when php finishes, the file also got deleted. Where do I do wrong here?

PHP:

$strSQL = file_get_contents("archdata.sql");
if (!empty($strSQL)) {
  $query=$conn->prepare($strSQL);
  if ($query->execute()) {
    sleep(5);  
    echo "1";
  } else {
    echo "Error: " . $strSQL;
  }
}

archdata.sql:

SET @path = 'C:Dataackups'   
SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112)  
SET @fileName = @path + 'ProdDB _' + @fileDate + '.BAK' 
BACKUP DATABASE ProdDB TO DISK=@fileName WITH STATS = 1 
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.1instance,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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...