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();
}
This script
<?php
/* Connect to a MySQL database using driver invocation */
$dsn = 'mysqldg';
$user = 'odbc_dg';
$password = '999999999';
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
gives the error *Connection failed: invalid data source name*
I have created an entry in /etc/odbc.ini as follows:
[mysqldg]
Description = DGDB
Driver = mysql537
Database = dg1
Servername = 99.99.99.99
UID = odbc_dg
PWD = 999999
SSLKeyFile = /etc/mysql/ssl/ck.pem
SSLCertFile = /etc/mysql/ssl/cc.pem
SSLCAFile = /etc/mysql/ssl/c1.pem
/etc/odbcinst.ini has the following entry:
[mysql537]
Description = MySQL driver for Plesk
Driver = /usr/lib/odbc2/lib/libmyodcb5w.so
Setup = /usr/lib/odbc2/lib/libmyodbc5w.so
The entry in odbcinst.ini works with a non-DSN connection.
I'm obviously missing something, can anyone help? Thanks.
UPDATED....
I have tried Your Common Sense's code as follows:
<?php
$host = '46.99.199.199';
$db = 'dg';
$user = 'odbc_dg';
$pass = '999999';
$charset = 'utf8mb4';
$options = array(
PDO::MYSQL_ATTR_SSL_KEY => '/etc/mysql/ssl/ck.pem',
PDO::MYSQL_ATTR_SSL_CERT => '/etc/mysql/ssl/cc.pem',
PDO::MYSQL_ATTR_SSL_CA => '/etc/mysql/ssl/c1.pem'
);
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
... but I get a connection fail message - Connection failed: SQLSTATE[HY000] [2002]
I think the problem is that the keys I have supplied only work with ODBC
For example this code, which uses odbc_connect works....
<?php
ini_set ('error_reporting', E_ALL);
ini_set ('display_errors', '1');
error_reporting (E_ALL|E_STRICT);
$user = "odbc_dg";
$pass = "99999";
$connection = "Driver= {mysql537};Server=46.99.199.199;Database=dgdb;UID=dgdb;PWD=999999;sslca=/etc/mysql/ssl/c1.pem;sslkey=/etc/mysql/ssl/ck.pem;sslcert=/etc/mysql/ssl/cc.pem";
$con = odbc_connect($connection, $user, $pass);
$sql="SELECT Id from stk_item";
$rs=odbc_exec($con,$sql);
if (!$rs) {
exit("Error in SQL");
}
echo "<table><tr>";
echo "<th>Companyname</th>";
echo "<th>Contactname</th></tr>";
while (odbc_fetch_row($rs)) {
echo odbc_result($rs, "Id"), "\n";
}
odbc_close($con);
echo "</table>";
?>
My problem is that I want to connect to the remote database via pdo because that's the only type of connection allowed in the Drupal synchronising code.
I'm trying to open a connection to Amazon RDS MS-SQL from Hosting with MSSQL library with following code:
<?php
$dbhost = "xxxxxxx.rds.amazonaws.com";
$dbport = 1433;
$dbname = "xxxxx";
$dbuser = "xxxxxx";
$dbpass = "xxxxxxx";
try {
$dbh = new PDO ("dblib:host=$dbhost:$dbport;dbname=$dbname","$dbuser","$dbpass");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
and I am getting this error:
Failed to get DB handle: SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)
what is the best way for create a connection between PHP and SQL server that are seperate?(two server: server a SQL and server b PHP)
notice that I use wamp.
I read some articles like below but I want to know is there any new idea?
I test this code that works perfectly:
try{
$user = 'user';
$password = 'pass';
$server="localhost";//or server IP
$database="database";
$conn = odbc_connect("Driver={SQL Server};Server=$server;Database=$database;", $user, $password);
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
I use PDO_ODBC Method:
1- Install ODBC on server that has wamp and enable PHP_PDO_ODBC extension on your wamp
2- Use this code that supports UTF-8:
try{
$hostname = "IP";
$dbname = "database";
$username = "username";
$pw = "password";
$pdo = new PDO ("odbc:Driver={SQL Server Native Client 10.0};Server=$hostname;Database=$dbname; Uid=$username;Pwd=$pw;");
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
$query = $pdo->prepare("select field_name from table");
$query->execute();
for($i=0; $row = $query->fetch(); $i++){
echo iconv("CP1256","UTF-8", $row['field_name'])."<br>";
}
3- replace these Items with yours:
IP-database-username-password-field_name-table
4- sometimes you need use "SQL SERVER" instead of "SQL Server Native Client 10.0" and sometimes you need use "IP,port" instead of "IP" and sometimes you need use "ISO-8859-6" instead of "CP1256".
From the PHP manual: http://php.net/manual/en/pdo.construct.php
Example #1 Create a PDO instance via driver invocation
<?php
/* Connect to a SQL Server database using driver invocation */
$dsn = "sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName#12345abcde", "Password";
try {
$dbh = new PDO($dsn);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Just change the HOST ip to the IP and port of your mysql server.
I am trying to connect MS SQL Server 2012 with php. My OS is Linux Red Hat and I am using PHP 5.5.7 version. This is my connection function:
function connect_ms_sql()
{
try {
$hostname = "xxx";
$port = 111;
$dbname = "xxx";
$username = "xxx";
$pw = "xxx";
$dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname", "$username", "$pw");
} catch (PDOException $e) {
echo "Failed to get DB handle: " . $e->getMessage() . "\n";
exit;
}
unset($dbh);
}
When I run this function, it shows me error: Failed to get DB handle: could not find driver. How I can fix it? I tried with FreeTDS, same error. Please help me!