MSSQL database stuck in ‘restoring” state with PHP

I can execute the following in SSMS and the database will be fully backed up and restored under a new DB name:

USE [master]; BACKUP DATABASE PW_TEMPLATE TO DISK=N'C:PW_TEMPLATEPW_TEMPLATE_full.bak'
USE [master]; RESTORE DATABASE PW_TEST_0001 FROM DISK = N'C:PW_TEMPLATEPW_TEMPLATE_full.bak' WITH REPLACE, RECOVERY, MOVE 'PW_TEMPLATE' TO 'H:DATAPW_TEST_0001.mdf', MOVE 'PW_TEMPLATE_log' TO 'I:LOGSPW_TEST_0001_log.ldf'

If I use the same from within PHP, it stays stuck in “restoring” status.

What is the difference between doing it in SSMS or via PHP and how can I fix this issue?

I’m using:

Microsoft SQL Server 2014 (SP3) (KB4022619) - 12.0.6024.0 (X64) 
Sep  7 2018 01:37:51 
Copyright (c) Microsoft Corporation
Enterprise Edition (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)

PHP Code:

public function actionDeployDatabase($db_name)
{
    $backup = "USE [master]; BACKUP DATABASE PW_TEMPLATE TO DISK=N'C:PW_TEMPLATEPW_TEMPLATE_full.bak'";
    echo $backup . PHP_EOL;
    Yii::$app->db2->createCommand($backup)->execute();
    $restore = "USE [master]; RESTORE DATABASE __DBNAME__ FROM DISK = N'C:PW_TEMPLATEPW_TEMPLATE_full.bak' WITH REPLACE, RECOVERY, MOVE 'PW_TEMPLATE' TO 'H:DATA__DBNAME__.mdf', MOVE 'PW_TEMPLATE_log' TO 'I:LOGS__DBNAME___log.ldf'";
    $restore = $this->str_replace2('__DBNAME__', $db_name, $restore, -1, $count);
    echo $restore . PHP_EOL;
    Yii::$app->db2->createCommand($restore)->execute();
    echo "Done..." . PHP_EOL;
}

public function str_replace2($find, $replacement, $subject, $limit = -1, &$count = 0)
{
    $ptn = '/' . preg_quote($find, '/') . '/';
    return preg_replace($ptn, $replacement, $subject, $limit, $count);
}

}

Answer

Could you please give what this prints out echo $restore . PHP_EOL; by commenting out the str_replace2() on $restore?

$restore = "USE [master]; RESTORE DATABASE __DBNAME__ FROM DISK = N'C:PW_TEMPLATEPW_TEMPLATE_full.bak' WITH REPLACE, RECOVERY, MOVE 'PW_TEMPLATE' TO 'H:DATA__DBNAME__.mdf', MOVE 'PW_TEMPLATE_log' TO 'I:LOGS__DBNAME___log.ldf'";

This statement is using __DBNAME__ in a static string. Do you wish to use PW_TEST_0001 instead? If so then $restore needs to be dynamic.

Edit: This is a familiar issue with the PDO driver, the problem maybe in the internal drivers upon which the PDO is built. Changing the driver will help resolve the issue.