Error connecting to the database using PDO

0

I am trying to connect my web with a sql-server database (use Microsoft SQL Server Management Studio).

I have entered the database using SQL Server Authentication using username and password that I already had created. To expose my problem we will say the credentials are: Login: user / Password: 1234 and the database is called test

To make a test of the connection I used the following code:

<?php 
    $servername = 'DESKTOP-FHALK16\SQLEXPRESS';
    $connectionInfo = array("Database"=>"prueba", "UID"=>"usuario", "PWD"=>"1234", "CharacterSet"=>"UTF-8");
    $conn_sis = sqlsrv_connect($servername, $connectionInfo);

    if($conn_sis){
        echo "Hay conexión!!!";
    }else{
        echo "Fallo en la conexion";
        die(print_r(sqlsrv_errors(), true));
    }
?>

When executing the code I get a connection but when connecting to PDO it does not connect. PDO code:

$base = new PDO("sqlsrv:server = DESKTOP-FHALK16\SQLEXPRESS;Database=prueba", 'usuario', '1234');
$base ->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$base -> exec("SET CHARACTER SET utf8");

try{
    $query = "SELECT ID_USUARIO FROM USUARIOS";
    $resultado = $base -> prepare($query);
    $resultado->execute(array());

    while($row = $resultado -> fetch(PDO::FETCH_ASSOC)){ 
        echo $row['ID_USUARIO'];
    }
}catch(Exception $e){
    echo "Linea de error: " . $e->getLine();
}

I have the necessary drivers installed as shown in the image

    
asked by gmarsi 14.06.2017 в 23:42
source

2 answers

0

Change the following code

$base = new PDO("sqlsrv:server = DESKTOP-FHALK16\SQLEXPRESS;Database=prueba", 'usuario', '1234');

for this

$base = new PDO("sqlsrv:host=DESKTOP-FHALK16\SQLEXPRESS;dbname=prueba", 'usuario', '1234');

I hope it works for you

    
answered by 14.06.2017 в 23:50
0

If you have all the drivers installed correctly and you indicate the correct credentials, it should work as follows:

function conectar()
{

 /* $serverName = "sqlserver.example.com"; //remoto */
    $serverName = "(local)\sqlexpress"; //local   

    $database = "myDbName";
    $user = 'sqlserver_username';
    $pwd = 'password';
    try {
        $conn = new PDO("sqlsrv:server=$serverName;Database=$database", $user, $pwd,
                array(
                       //PDO::ATTR_PERSISTENT => true,
                         PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
                         PDO::ATTR_EMULATE_PREPARES => false //Importante
                     )
                 );
    return $conn; 
    catch(PDOException $e) 
    {
       die("Error connecting to SQL Server: " . $e->getMessage());
       return null;
     }
}

For more details: Microsoft, Example Application (PDO_SQLSRV Driver )

    
answered by 15.06.2017 в 01:22