Error trying to connect bd MSSQL Server using PDO [closed]

1

I can not access the MS SQL SERVER database using PDO. I've done everything, the best answer I got was with the code below, but I keep getting an error response:

  

Connection Error SQLSTATE [] (null) (severity 0)

My server is CentOS 5.11 (64 bit)

Any ideas?

<?php
  try {
    $hostname = "db-gadel-campinas.lexos.com.br,1500";
    $dbname = "LexManager_GadelCampinas";
    $username = "gadelview";
    $pw = "password";
    $pdo = new PDO ('dblib:host=$hostname;dbname=$dbname', '$username', '$pw');
  } catch (PDOException $e) {
    echo "Erro de Conexão " . $e->getMessage() . "\n";
    exit;
  }
?>

I changed the code and the connection to sqlserver seems to work. Now it's figuring out how to query the table and show the data :). Any tips?

Is the code correct?

<?php
  try {
    $hostname = "db-gadel-campinas.lexos.com.br";
    $port = 1500;
    $dbname = "LexManager_GadelCampinas";
    $username = "gadelview";
    $pw = "password";
    $dbh = new PDO ("dblib:host=$hostname:$port;dbname=$dbname","$username","$pw");
    echo "Conexão ok";
  } catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
}
?>
    
asked by anonymous 04.01.2017 / 04:02

1 answer

1

When I run the script in windows I believe that the comma is used like this ( dblib:host=HOST,PORTA ):

new PDO('dblib:host=db-gadel-campinas.lexos.com.br,1500;dbname=<banco>', '<usuario>', '<senha>');

If it's linux (or like-unix) I think the correct one is to use : , like this:

new PDO('dblib:host=db-gadel-campinas.lexos.com.br:1500;dbname=<banco>', '<usuario>', '<senha>');

Aside from the fact that you used ' apostrophes and tried to pass variables like '$variavel' , php does not recognize this as a variable, it will think it's only a string , I can then concatenate or use normal quotes "

Do this:

$hostname = "db-gadel-campinas.lexos.com.br:1500";
$dbname = "LexManager_GadelCampinas";
$username = "gadelview";
$pw = "password";
$pdo = new PDO ('dblib:host=' . $hostname . ';dbname='. $dbname, $username, $pw);

Or with quotation marks (all other parameters do not require quotation marks)

$hostname = "db-gadel-campinas.lexos.com.br:1500";
$dbname = "LexManager_GadelCampinas";
$username = "gadelview";
$pw = "password";
$pdo = new PDO ("dblib:host=$hostname;dbname=$dbname", $username, $pw);

If the problem really is with the comma, you can do this:

if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
    $hostname = "db-gadel-campinas.lexos.com.br,1500";
} else {
    $hostname = "db-gadel-campinas.lexos.com.br:1500";
}
    
05.01.2017 / 20:40