PHP connect to SQL server on different machines - php

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

Related

Backup SQL Server database using 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;
?>

WAMP localhost install SQLSRV for connecting to database

I'm using WAMP to run my code locally.
Now I want to connect to a microsoft SQL server database using PHP.
// connection with callstats DB
$serverName = "IP, 1433"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"CDR", "UID"=>"username", "PWD"=>"password");
Im using:
$conn_CDR = sqlsrv_connect( $serverName, $connectionInfo);
$params = array();
And then for a query:
$result = sqlsrv_query($conn_CDR, "", $params);
But then I get this error:
Warning: sqlsrv_query() expects parameter 1 to be resource, boolean given
Now I know I need to install sqlsrv into my localhost.
I'm using PHP 7.2.14 so I installed php_sqlsrv_72_ts.dll to my C:\localhost\bin\php\php7.2.14.
Also I added this line to my php.ini.
extension=php_sqlsrv_72_ts.dll
Then I restarted my WAMPserver, and runned my code again, but I still get the same result.
I also tried adding the file to C:\localhost\bin\apache\apache2.4.37\binbut no succes either.
Does anyone know why this error keeps occurring and how to fix it?
I solved it by installing the Microsoft ODBC Driver for SQL Server onto my computer.
Then I restarted my WAMP server and it worked!
Download ODBC Driver here
This gave me the info I needed to solve my error:
if ($conn_CDR === false) {echo "Error (sqlsrv_connect): ".print_r(sqlsrv_errors(), true);}
$conn_CDR = sqlsrv_connect( $serverName, $connectionInfo);
$params = array();
$sql = "your sql query";
$result = sqlsrv_query($conn_CDR, $sql, $params));
See the manual here https://www.php.net/manual/en/function.sqlsrv-query.php
like this example:-
$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}

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();
}

Can't Connect to local server using PDO?

I have been playing around for PHP with a while. This is how i connect to sql server and it works:
$serverName = "SNAME";
$connectionInfo = array( "Database"=>"DBNAME", "UID"=>"USERNAME", "PWD"=>"PASSWORD");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sql = "SELECT X FROM myTable";
$query = sqlsrv_query($conn,$sql);
if ($query === false){
echo "Could not link to SQL Server";
}
while ($row = sqlsrv_fetch_array($query))
{
$ARRAY[] = "$row[X]";
}
Server SNAME is on the local network, and i can connect to it from my computer using Sql Management Studio.
Now looking online and other places I have realized PDO is the better way to go. So I have been trying to connect to my server using PDO, by following examples online. Here is the code:
$username = "USERNAME";
$password = "PASSWORD";
try{
$conn = new PDO('mysql: host=SNAME;port=1433;dbname=DBNAME',$username,$password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$data = $conn->query('SELECT X FROM myTable');
foreach($data as $row) {
print_r($row);
}
}
catch{
echo 'ERROR: ' . $e->getMessage();
}
When i run this i get this on my page:
ERROR: SQLSTATE[HY000] [2002] No connection could be made because the
target machine actively refused it.
Now i know my other information is right since i can use the top block and sql management studio. Is there anyother library or something special needed. Is there problem with my code?
UPDATE
I ran this in my SQL Management Studio to check my port and it gave me 1433.
SELECT DISTINCT local_tcp_port FROM sys.dm_exec_connections WHERE local_tcp_port IS NOT NULL
In one example, you are using sqlsrv_connect, but in the other you tell PDO to connect to a 'mysql:' database.
You need to use the correct DSN string for a SQL Server connection.
$conn = new PDO('sqlsrv:Server=SNAME,1433;Database=DBNAME',$username,$password);
Manual: http://php.net/manual/en/ref.pdo-sqlsrv.connection.php
P.S. Make sure you have PDO_SQLSRV installed. http://php.net/manual/en/ref.pdo-sqlsrv.php

Trouble connecting to remote SQL Server 2005 with PHP using mssql

I've been struggling with this for a ridiculous amount of time and I'm not sure what to do. I'm using PHP 5.4 on a GoDaddy Linux shared hosting account with the mssql module enabled. The database I'm trying to reach is hosted elsewhere. I'm trying to connect via mssql_connect. I've tried
$con = mssql_connect('<ip address>', 'user', 'pass');
as well as
$con = mssql_connect('<ip address>\<instance name>', 'user', 'pass');
And the above two with port numbers. But I still get the "Unable to connect to server" error. I've made sure SQL Server is accepting outside connections and SQL Agent is running. I can't use PDO with sqlserv because of GoDaddy, mssql is the only module I'm able to use.
Does anyone have any ideas as to what could be wrong?
Try using SQLSRV functions:
<?php
$serverName = "ipAddress\instanceName";
$connectionInfo = array( "Database"=>"dbName", "UID"=>"user", "PWD"=>"pass" );
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
$sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)";
$params = array(1, "some data");
$stmt = sqlsrv_query( $conn, $sql, $params);
if( $stmt === false ) {
die( print_r( sqlsrv_errors(), true));
}
?>
Note: you don't need to inform the instance name in some cases. Try with IP address alone first.

Categories