Connect PHP with SQL SERVER

6

I have searched everywhere, but I can not find an answer or find incomplete answers.

What is the complete way to connect PHP with SQL Server 2008?

    
asked by Guillermo Ricardo Spindola Bri 29.04.2016 в 17:39
source

6 answers

8

First you must download the Driver or dll of sql Server and configure it as shown in the link below, it is simple and it will only take you about 10 minutes to do it: PHP SQLServer Driver

Then try with:

 resource sqlsrv_connect ( string $serverName [, array $connectionInfo ] )

Opens a connection to a Microsoft SQL Server database. By default, the connection is attempted using Windows authentication. To connect using SQL Server authentication, include "UID" and "PWD" in the array of connection options. Parameters

serverName

El nombre del servidor en el que se ha establecido una conexión. Para conectar a una instancia específica, poner una barra invertida después del nombre de servidor e indicar el nombre de la instancia (e.g. NombreServidor\sqlexpress).

connectionInfo

Un array asociativo que especifica las opciones de conexión al servidor. Si no se ha especificado ningún valor para el UID y PWD, la conexión se intentará utilizando la autenticación Windows. Para una lista completa de claves soportadas, ver » Opciones de Conexión SQLSRV.

Return values

A connection resource. If the connection can not be opened, the FALSE value is returned. Examples

Example # 1 Connect using Windows authentication.

<?php
$serverName = "serverName\sqlexpress"; //serverName\instanceName

// Puesto que no se han especificado UID ni PWD en el array  $connectionInfo,
// La conexión se intentará utilizando la autenticación Windows.
$connectionInfo = array( "Database"=>"dbName");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Conexión establecida.<br />";
}else{
     echo "Conexión no se pudo establecer.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Example # 2 Connect specifying username and password.

<?php
$serverName = "serverName\sqlexpress"; //serverName\instanceName
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Conexión establecida.<br />";
}else{
     echo "Conexión no se pudo establecer.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Example # 3 Connect to a specific port.

<?php
$serverName = "serverName\sqlexpress, 1542"; //serverName\instanceName, portNumber (por defecto es 1433)
$connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password");
$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {
     echo "Conexión establecida.<br />";
}else{
     echo "Conexión no se pudo establecer.<br />";
     die( print_r( sqlsrv_errors(), true));
}
?>

Notes

By default, the sqlsrv_connect () function uses the connection by grouping to improve the functioning of the connection. To disconnect the operation in group mode (eg forcing a new connection on each call), configure the "ConnectionPooling" option in the array $ connectionOptions to 0 (or FALSE). For more information, see »SQLSRV connection queue.

The SQLSRV extension does not have a specific function to change to which database it is connected to. The target database is specified in the $ connectionOptions option array that is passed to sqlsrv_connect. To change the database in an already open connection, execute the following sql statement "USE dbName" (eg sqlsrv_query ($ conn, "USE dbName")).

    
answered by 29.04.2016 в 19:32
5

In my experience, I've used PDO (PHP Data Object) to make connections to databases MySQL and SQL SERVER .

PDO_DBLIB is the driver to implement SQL Server in PHP.

The advantage of PDO in this case is that it accepts 12 database managers. The disadvantage compared to the Microsoft Driver PHP for SQL Server , is that this is more tuned, or so I understand.

In extended, the properties of connection to the database, are usually in php in a file called db_config.php , this will be my file to present the connection example.

db_config.php

<?php

define("DRIVER_SQL", "dblist:host");
define("DATABASE", "ejemplo");
define("PORT",     "10060");
define("HOSTNAME", "localhost");
define("USERNAME", "admin");
define("PASSWORD", "1234");


define("URI", DRIVER_SQL . HOSTNAME . ":" . PORT . ":dbname=" . DATABASE);

?>

And this is the file, where you will have prepared queries and / or make the connection.

db.php

<?php

// ...

function connect() {
    try {
        $pdo = new PDO(URI, USERNAME, PASSWORD);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $pdo;
    } catch (PDOException $e) {
        echo("PDOException: ".$e);
            return false;
    }
}

// ...

?>

Here you will find many connection examples: Link

    
answered by 29.04.2016 в 20:02
1

In case your application server is in linux, I recommend you use FreeTDS which is a native library to talk to sql server and that is much faster than other libraries.

    
answered by 30.04.2016 в 16:46
1

Well the idea is to install the driver correctly for php.

In Ubuntu it's with freetds apt-get install freetds-bin freetds-common freetds-dev - See more at: link

In Centos it is the mssql-php5

Well that's how fast you should be based on searching dirver sql linux (distribution) mssql

From there, most connections are the same

$conexion=mssql_connect($serverName,$uid,$pwd);

mssql_select_db($base_datos,$conexion);
    
answered by 30.04.2016 в 23:21
0

My brother, I hope this solution helps you.

Install the xampp of this version:

link

once installed download these dll.

php_pdo_sqlsrv_56_ts.dll
php_sqlsrv_56_ts.dll

once installed you go in your xampp

CONFIG - > PHP.INI

And you add this

;extension=php_pdo_sqlsrv_56_ts.dll
;extension=php_sqlsrv_56_ts.dll

Now when you have already placed you go to your disk C then xampp then php then dll and the dll that you downloaded downloaded it there.

and it would be everything.

then try the connection.

to connect from your sql server to your php

<?php
$serverName = '';
$uid = 'sa';
$pwd = '';
$databaseName = 'dbdatos';
$connectionInfo = array( 'UID'=>$uid,'PWD'=>$pwd,'Database'=>$databaseName);



$conn = sqlsrv_connect($serverName,$connectionInfo);


if($conn){echo ''; }else{echo 'Connection failure<br />';die(print_r(sqlsrv_errors(),TRUE));}


?>

I hope to see you helped.

    
answered by 03.02.2018 в 16:09
-2

It worked for me with this code:

$servidor = "NOMBREPC\SQLEXPRESS";
$database = "PRUEBA";
$info = array('Database'=>$database);
$cn = sqlsrv_connect($servidor, $info);
    
answered by 26.07.2016 в 15:24