Aranoxf5
Aranoxf5

Reputation: 3

Cant get php to connect to sql. Get error Connection failed: php_network_getaddresses: getaddrinfo failed: No such host is known.

I have scoured google, and stackover flow, and just cant get to the bottom of this issue. I cannot get the following php code to connect to SQL. Its a simple php web document, that i am using to test out some things. SQL is sqlexpress 2016, and its running on IIS with php 7.x installed. PHP code executes fine, so its something with the code or the database is my guess. Things I've tried:

The PDO code ive used is:

<?php
$servername = 'RemoteServerName\SqlInstance';
$username = 'iislogon';
$password = 'password';

try {
$conn = new PDO("mysql:host=$servername;dbname=netdata", $username, 
$password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully"; 
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
?>

The mysqli code is:

<?php
$servername = 'RemoteServerName\SqlInstance';
$username = 'iislogin';
$password = 'password';
$dbname = 'netdata';
?>
<?php $conn = new mysqli($servername, $username, $password, $dbname); ?>

<?php 
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} 
echo "Connected successfully";?>

Both return the same error of host not found. What other issues could be causing this? Im new to coding php so any help would be appreciated.

Upvotes: 0

Views: 352

Answers (3)

Eriks Klotins
Eriks Klotins

Reputation: 4180

Look at this description http://php.net/manual/en/pdo.construct.php and specifically:

In general, a DSN consists of the PDO driver name, followed by a colon, followed by the PDO driver-specific connection syntax. Further information is available from the PDO driver-specific documentation.

Are you sure your dsn is correct and you have the PHP module enabled? See http://php.net/manual/en/ref.pdo-mysql.php

Upvotes: 1

Dionei Miodutzki
Dionei Miodutzki

Reputation: 657

mysqli and PDO starting with mysql: are supposed to connect to MySQL, not SQLExpress.

If you want to use SQLExpress you should use something like sqlsrv_connect or adjust your pdo string to a SQLExpress compatible one.

Take a look at this thread too.

Upvotes: 1

Car
Car

Reputation: 13

I think you didn't escape your backslash with another backslash. Try this:

<?php
$servername = 'RemoteServerName\\SqlInstance';
?>

Upvotes: 0

Related Questions