Backup SQL Server database using PHP - php

I am trying to backup a MS SQL database calling a Stored Procedure using PHP.
When I execute de SP on SSMS, everything works fine. However, when I call it from the PHP script, I can see a ".bak" in the backup folder and right after the PHP finishes processing, the BackUp.bak file disappears.
Here is the Stored Procedure:
DECLARE #date VARCHAR(10)
SET #date = (SELECT date FROM tbl_date)
Declare #fileName VARCHAR(100)
SET #fileName = ('C:\db_backup\BackUp_' + #date + '.bak')
BACKUP DATABASE DbName
TO DISK = #fileName
WITH FORMAT,
MEDIANAME = 'SQLServerBackups',
NAME = 'Full Backup of DbName';
Below is the PHP code I call the SP:
$serverName = "server";
$connectionInfo = array( "Database"=>"DbName", "UID"=>"UserName", "PWD"=>"P#ssword", "CharacterSet"=>"UTF-8", "ReturnDatesAsStrings" => "false");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$BackupDB = "Exec DBBackup";
sqlsrv_query($conn, $BackupDB);
I am running Apache 2.4.46 and SQL Server Express 2019.
My goal is to create a ".bak" file using PHP.
I tried using a SP because the original code is written in Classic ASP and it works flawlessly this way.
I am open to try different approaches.
Thank you.

Explanations:
You are using PHP Driver for SQL Server, so the following explanations are an additional option for solving your problem:
It seems that this issue is probably a driver specific problem. SQL Server fills the output buffer of the connection with the result sets that are created by the batch - information about the count of the affected rows (in a case of INSERT\DELETE\UPDATE statements for example) or progress status (returned from BACKUP\RESTORE DATABADE statements). These result sets must be processed by the PHP script. It seems that this behavior is by design and the PHP script should flush all the pending result sets. After the result sets are fetched, SQL Server completes the execution of the batch. The appropriate functions\methods that you need to use are sqlsrv_next_result() (for SQLSRV version of the driver) and PDOStatement::nextRowset() (for PDO_SQLSRV version of the driver).
For the SQLSRV version of the driver you need to change the error and warning handling using sqlsrv_configure("WarningsReturnAsErrors", 0);.
Examples:
I'm able to reproduce the issue from the question and the following examples are working solutions:
Using SQLSRV version of the driver:
<?php
// Server information
$server = "server\instance,port";
$database = "database";
$uid = "username";
$pwd = "password";
// Configuration
sqlsrv_configure("WarningsReturnAsErrors", 0);
// Connection
$cinfo = array(
"UID" => $uid,
"PWD" => $pwd,
"Database" => $database
);
$conn = sqlsrv_connect($server, $cinfo);
if ($conn === false) {
echo "Unable to connect.";
die( print_r( sqlsrv_errors(), true));
}
// Statement
$sql = "
DECLARE #date VARCHAR(19)
SET #date = CONVERT(VARCHAR(19), GETDATE(), 126)
SET #date = REPLACE(#date, ':', '-')
SET #date = REPLACE(#date, 'T', '-')
DECLARE #fileName VARCHAR(100)
SET #fileName = ('d:\backup\BackUp_' + #date + '.bak')
BACKUP DATABASE dbname
TO DISK = #fileName
WITH
FORMAT,
STATS = 1,
MEDIANAME = 'SQLServerBackups',
NAME = 'Full Backup of dbname';
";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false) {
echo "Unable to execute query.";
die( print_r( sqlsrv_errors(), true));
}
// Clear buffer
while (sqlsrv_next_result($stmt) != null){};
echo "Success";
// End
sqlsrv_free_stmt($stmt);
sqlsrv_close($conn);
?>
Using PDO_SQLSRV version of the driver:
<?php
// Server information
$server = "server\instance,port";
$database = "database";
$uid = "username";
$pwd = "password";
// Connection
try {
$conn = new PDO("sqlsrv:server=$server;Database=$database", $uid, $pwd);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch( PDOException $e ) {
die( "Error connecting to SQL Server".$e->getMessage());
}
// Statement
$sql = "
DECLARE #date VARCHAR(19)
SET #date = CONVERT(VARCHAR(19), GETDATE(), 126)
SET #date = REPLACE(#date, ':', '-')
SET #date = REPLACE(#date, 'T', '-')
DECLARE #fileName VARCHAR(100)
SET #fileName = ('d:\backup\BackUp_' + #date + '.bak')
BACKUP DATABASE dbname
TO DISK = #fileName
WITH
FORMAT,
STATS = 1,
MEDIANAME = 'SQLServerBackups',
NAME = 'Full Backup of dbname';
";
try {
$stmt = $conn->prepare($sql);
$stmt->execute();
} catch (PDOException $e) {
die ("Error executing query. ".$e->getMessage());
}
// Clear buffer
try {
while ($stmt->nextRowset() != null){};
echo "Success";
} catch (PDOException $e) {
die ("Error executing query. ".$e->getMessage());
}
// End
$stmt = null;
$conn = null;
?>

Related

php - how execute a sqlsrv stored procedure

I have a successful connection to SQL Server using SQLSRV in my PHP script:
$name = 'SERVERNAME';
$db = 'DBNAME';
$par = array("Database"=>$db);
$conn = sqlsrv_connect($name, $par);
Also I have the following T-SQL script:
Declare #dt datetime;
SET #dt = GETDATE();
EXEC oik..SrezLTGES #Cat = 'Ë', #Ids = '140539,140540,140589,150395,180395,180396,180445',#Time = #dt
The procedure parameters are:
I don't know how to execute this query in PHP. Any ideas?
A possible approach here is to parameterize the statement and use sqlsrv_query(). As is mentioned in the documentation, the sqlsrv_query function is well-suited for one-time queries and should be the default choice to execute queries unless special circumstances apply and sqlsrv_query function does both statement preparation and statement execution, and can be used to execute parameterized queries.
The stored procedure has varchar parameters (and I'm almost sure, that you are using a cyrillic collation), so you may need to use the appropriate encoding ("CharacterSet" => "UTF-8" or "CharacterSet" => SQLSRV_ENC_CHAR in the connection options) and/or character set conversion on the parameters values (with iconv() for example). Reading UTF-8 all the way through is a good starting point.
If the stored procedure returns data, you may try to use sqlsrv_fetch_array() to retrieve the returned data. You may also use SET NOCOUNT ON to prevent SQL Server from passing the count of the affected rows as part of the result set.
The following example, based on your code, is a possible solution to your problem:
<?php
// Connection
$server = "SERVERNAME";
$database = "DBNAME";
$cinfo = array(
"CharacterSet" => "UTF-8",
"Database" => $database
);
$con = sqlsrv_connect($server, $cinfo);
if ($con === false) {
echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);
exit;
}
// Statement
$sql = "
SET NOCOUNT ON;
DECLARE #dt datetime;
SET #dt = GETDATE();
EXEC oik..SrezLTGES
#Cat = ?,
#Ids = ?,
#Time = #dt,
#TimeIsSummer = 1,
#ShowSystemTime = 1
";
$params = array("Ë", "140539,140540,140589,150395,180395,180396,180445");
$stmt = sqlsrv_query($con, $sql, $params);
if ($stmt === false) {
echo "Error (sqlsrv_query): ".print_r(sqlsrv_errors(), true);
exit;
}
// Data
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo print_r($row, true);
}
// End
sqlsrv_free_stmt($stmt);
sqlsrv_close($con);
?>

Length of output parameter in sqlsrv - 01004 (Data truncated)

I have stored procedures in SQL Server that output data as xml datatype. When I try to get the output parameter in PHP with PHP Driver for SQL Server (sqlsrv extension) and the string is longer than 4000 I get an SQL Error (SQLSTATE 01004 (Data truncated)).
Here is a short example:
Stored Procedure:
CREATE PROCEDURE pr_getlargexml
#xml xml OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SET #xml =
(
SELECT *
FROM largeTable
FOR XML RAW, ELEMENTS, TYPE, ROOT('xml')
);
END;
GO
PHP code:
$serverName = "localhost\SQL2012TEST";
$connectionInfo = array("Database" => "TEST", "UID" => "", "PWD" => "");
$conn = sqlsrv_connect($serverName, $connectionInfo);
if ($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
$retval = '';
$query = sqlsrv_query($conn, 'EXEC pr_getlargexml ?',array(array(&$retval,SQLSRV_PARAM_OUT,SQLSRV_PHPTYPE_STRING('UTF-8'),SQLSRV_SQLTYPE_XML)));
if ($query === false) {
die(print_r(sqlsrv_errors(), true));
}
echo "<pre>";
\var_dump($retval);
echo "</pre>";
If the xml is shorter than 4000, it works fine. I also tried to use nvarchar(max) as datatype in sql and SQLSRV_SQLTYPE_NVARCHAR('max') in php as sqltype, but I get the same Error.
Has anyone a solution for my problem?

Can't connect to MS SQL server [duplicate]

I want to use PHP to connect to sql server database.
I installed xampp 1.7.0(php 5.2) and SQLSRV20. I've added the extensions in php.ini and I get this error:
Warning: mssql_connect() [function.mssql-connect]: Unable to connect to
server: 10.85.80.229 in C:\xampp\htdocs\xampp\test.php on line 07
Code:
<?php
$myServer = "10.85.80.229";
$myUser = "root";
$myPass = "pass";
$myDB = "testdb";
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
?>
What does this error message mean and how do I connect to SQL Server?
enable mssql in php.ini
;extension=php_mssql.dll
to
extension=php_mssql.dll
<?php
$serverName = "ServerName";
$uid = "sqlusername";
$pwd = "sqlpassword";
$databaseName = "DBName";
$connectionInfo = array( "UID"=>$uid,
"PWD"=>$pwd,
"Database"=>$databaseName);
/* Connect using SQL Server Authentication. */
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$tsql = "SELECT id, FirstName, LastName, Email FROM tblContact";
/* Execute the query. */
$stmt = sqlsrv_query( $conn, $tsql);
if ( $stmt )
{
echo "Statement executed.<br>\n";
}
else
{
echo "Error in statement execution.\n";
die( print_r( sqlsrv_errors(), true));
}
/* Iterate through the result set printing a row of data upon each iteration.*/
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))
{
echo "Col1: ".$row[0]."\n";
echo "Col2: ".$row[1]."\n";
echo "Col3: ".$row[2]."<br>\n";
echo "-----------------<br>\n";
}
/* Free statement and connection resources. */
sqlsrv_free_stmt( $stmt);
sqlsrv_close( $conn);
?>
http://robsphp.blogspot.ae/2012/09/how-to-install-microsofts-sql-server.html
if your using sqlsrv_connect you have to download and install MS sql driver for your php. download it here http://www.microsoft.com/en-us/download/details.aspx?id=20098
extract it to your php folder or ext in xampp folder
then add this on the end of the line in your php.ini file
extension=php_pdo_sqlsrv_55_ts.dll
extension=php_sqlsrv_55_ts.dll
im using xampp version 5.5 so its name php_pdo_sqlsrv_55_ts.dll & php_sqlsrv_55_ts.dll
if you are using xampp version 5.5 dll files is not included in the link...hope it helps
Try this code
$serverName = "serverName\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$server_name = "your server name";
$database_name = "your database name";
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$database_name;ConnectionPooling=0", "user_name", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
Use localhost instead of your IP address.
e.g,
$myServer = "localhost";
And also double check your mysql username and password.
for further investigation: print out the mssql error message:
$dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Could not connect to database: ".mssql_get_last_message());
It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:
$myServer = "10.85.80.229:1443";
or
$myServer = "10.85.80.229,1443";
$dbhandle = sqlsrv_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
Hope it help.
first download below software
https://www.microsoft.com/en-us/download/details.aspx?id=30679 - need to install
https://www.microsoft.com/en-us/download/details.aspx?id=20098 - when you run this software . it will extract dll file.
and paste two dll file(php_pdo_sqlsrv_55_ts.dll,extension=php_sqlsrv_55_ts.dll) this location C:\wamp\bin\php\php5.6.40\ext\ (pls make sure your current version)
2)edit php.ini file
add below line
extension=php_pdo_sqlsrv_55_ts.dll
extension=php_sqlsrv_55_ts.dll
Please refer screenshort
add dll in your php.ini file
MS SQL connect to php
Install the drive from Microsoft website
After install, you will get some files. Store it in your system temp folder
Check your php version, thread or non thread, and window bit - 32 or 64
(Thread or non thread, this is get you by phpinfo())
According to your system & xampp configration (php version and all) copy 2 files (php_sqlsrv & php_pdo_sqlsrv) to xampp/php/ext folder .
Add to php.ini file :
extension=php_sqlsrv_72_ts_x64
extension=php_pdo_sqlsrv_72_ts_x64
(php_sqlsrv_72_ts_x64.dll and php_pdo_sqlsrv_72_ts_x64.dll are the files which you copied in 4th step)
Next here is the Php Code to connect to database :
$serverName ="DESKTOP-me\\MSSQLSERVER01"; (servername\\instanceName)
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array("Database"=>"testdb","CharacterSet"=>"UTF-8");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
//echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
//$sql = "INSERT INTO dbo.master ('name') VALUES ('test')";
$sql = "SELECT * FROM dbo.master";
$stmt = sqlsrv_query( $conn, $sql );
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
echo $row['id'].", ".$row['name']."<br />";
}
sqlsrv_free_stmt( $stmt);
For those who want to connect to database(MSSQL) using Windows Auth, mssql_connect' was removed in the 7.0 PHP version. So you can use this instead;
$serverName="serverName";
$uid = '';
$pwd = "";
$dbase = "nameOfDB";
$conninfro = array("Database"=>$dbase, "UID"=>$uid, "PWD"=>$pwd);
$con = sqlsrv_connect( $serverName, $conninfro);
if( $con === false){
die( print_r( sqlsrv_errors(), true));
}
Take a look at the matrix to understand the compatibility of different versions of Windows/SQL Server/PHP drivers.
Download PHP driver dll -
https://github.com/microsoft/msphpsql/releases/
Copy the dll files to
/ext folder.
Edit php.ini and add dll names under Dynamic
Extensions.
Restart the webserver -Apache or IIS
Eg: using 8.1 version with SQL Server 2019.
extension=php_sqlsrv_81_ts
extension=php_pdo_sqlsrv_81_ts
Database Connection test Code - https://www.php.net/manual/en/function.sqlsrv-connect.php
I've been having the same problem (well I hope the same). Anyways it turned out to be my version of ntwdblib.dll, which was out of date in my PHP folder.
http://dba.fyicenter.com/faq/sql_server_2/Finding_ntwdblib_dll_Version_2000_80_194_0.html
For the following code you have to enable mssql in the php.ini as described at this link: http://www.php.net/manual/en/mssql.installation.php
$myServer = "10.85.80.229";
$myUser = "root";
$myPass = "pass";
$myDB = "testdb";
$conn = mssql_connect($myServer,$myUser,$myPass);
if (!$conn)
{
die('Not connected : ' . mssql_get_last_message());
}
$db_selected = mssql_select_db($myDB, $conn);
if (!$db_selected)
{
die ('Can\'t use db : ' . mssql_get_last_message());
}
$serverName="ServerName";
$uid = 'sa';
$pwd = "password";
$dbase = "dbname";
$conninfro = array("Database"=>$dbase, "UID"=>$uid, "PWD"=>$pwd);
$con = sqlsrv_connect( $serverName, $conninfro);
if( $con === false){
die( print_r( sqlsrv_errors(), true));
}
you can use PDO.
1-you must use php_pdo_sqlsrv_xx_nts.dll and php_sqlsrv_xx_nts.dll extensions.
note that you must use the proper version of those for your PHP.
2- use this code
$servername = "IP";
$username = "";
$password = "";
$db='';
try {
$conn = new PDO("sqlsrv:Server=$servername;Database=$db", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
and then use this code:
$stmt=$conn->prepare("select * from table");
$stmt->execute();
$result=$stmt->fetchall();
Try this to be able to catch the thrown exception:
$server_name = "your server name";
$database_name = "your database name";
try {
$conn = new PDO("sqlsrv:Server=$server_name;Database=$database_name;ConnectionPooling=0", "user_name", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
$e->getMessage();
}

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:\Data\backups\'
SELECT #fileDate = CONVERT(VARCHAR(20),GETDATE(),112)
SET #fileName = #path + 'ProdDB _' + #fileDate + '.BAK'
BACKUP DATABASE ProdDB TO DISK=#fileName WITH STATS = 1
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.

PHP connect to SQL server on different machines

I have a PHP website on a Windows machine and would like to insert data DIRECTLY to SQL database which is located on IIS server on a different machine?
Which approach shall I follow?
**My initial thought was to divert to a PHP page hosted by IIS that executes a query and then redirect back to my website. However, I prefer something easier and less complicated approach.
IIS is on Windows Server 2008 R2.
Your help is appreciated very much. Thanks!
If you're using PHP, you can open a connection to a database on another machine using PDO:
$remotedb = new PDO("*dbtype*:dbname=*dbname*;host=*addressOfOtherMachine*", $user, $password);
http://www.php.net/manual/en/class.pdo.php
I use SQLSRV in PHP to connect to a database on an IIS6 machine with 2008 R2. I believe the remote machine must allow remote connections and needs to be turned on through the settings if it isn't. Here is what my connection string looks like:
<?php
/* NEW CONNECTION FOR SQLSRV DRIVER (for MSSQL access) */
$uid = "username";
$pwd = "password";
$DB = "database_name";
$serverName = "ip_address_of_remote_server (example: 192.168.0.25)";
$connectionInfo = array("UID" => $uid, "PWD" => $pwd, "Database"=> $DB, "ReturnDatesAsStrings" => true);
$conn = sqlsrv_connect( $serverName, $connectionInfo);
?>
Here is a sample parameterized insert query using the connection:
<?php
$p1 = "values passed from a form";
$p2 = "values passed from a form";
$p3 = "values passed from a form";
$params = array(
array(&$p1, null, null, SQLSRV_SQLTYPE_VARCHAR(50)),
array(&$p2, null, null, SQLSRV_SQLTYPE_DATETIME),
array(&$p3, null, null, SQLSRV_SQLTYPE_VARCHAR(50))
);
$sql = "INSERT INTO database_name (column1, column2, column3) values (?,?,?)";
$stmt = sqlsrv_prepare($conn, $sql, $params);
if( !$stmt ) { die( print_r( sqlsrv_errors(), true)); }
if(sqlsrv_execute( $stmt ) === false ) { die( print_r( sqlsrv_errors(), true)); }
?>
For more SQLSRV params, visit http://msdn.microsoft.com/en-us/library/cc626305.aspx

Categories