0

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:

  • I've ran an echo in php to resolve the name, and it resolves it fine.
  • I've connected from a separate server to the sql server using tcp, and it connects fine.
  • I've tried both PDO connection, and mysqli and both come back with same error.

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.

0

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This solved my issue. Once i installed the sqlsrv extensions and changed my connection string to that, it solved my issue. Thank you.
1

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

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.