简体   繁体   中英

Using PHP connect Microsoft SQL Server 2014

I am trying to connect to a Microsoft SQL Server 2014 using php. I have XAMPP installed in my machine and I've tried to using PHP code to connect Microsoft SQL Server, but can't work. Below is my coding:

<?php

$host = "DELL-INSPIRON-W\SQLEXPRESS";
$username = "sa";
$password = "654321bb?";
$schema = "payment_record";

$mysql_con=mysqli_connect($host, $username, $password,$schema);
// Check connection
if (mysqli_connect_errno())
{
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    exit;
    }else{

    }

?>

Below is my Microsoft SQL Server 2014 login page:

登录页面

Below is my Microsoft SQL Server database:

在此处输入图像描述

The error show me: Failed to connect to MySQL: php_network_getaddresses: getaddrinfo failed: No such host is known.

I am trying to connect MySQL Query Browser, it can work, only Microsoft SQL Server 2014 can't work.

First you need to install the correct SQL-server driver for you php version. Here is a link to install SQL Driver for php 7.3:

https://docs.microsoft.com/en-us/sql/connect/php/download-drivers-php-sql-server?view=sql-server-ver15

Then you need to change your script of php connection. Now looks like you are trying to connect to MySQL instead of SQL-Server. Here is a script that I used before:

<?php
$serverName = 'x.x.x.x';
$connectionInfo = array('Database'=>'schema-name','UID'=>'user','PWD'=>'password');
$conn=sqlsrv_connect($serverName,$connectionInfo);

if($conn){
     echo "Connected.<br />";
}else{
     echo "Unable to connect<br />";
     die( print_r(sqlsrv_errors(), true));
}
?>

Where xxxx is the IP address of your SQL-Server and 'user' and 'password' must be your authentication info.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM