问题
what is the best way for create a connection between PHP and SQL server that are seperate?(two server: server a SQL and server b PHP) notice that I use wamp.
I read some articles like below but I want to know is there any new idea?
I test this code that works perfectly:
try{
$user = 'user';
$password = 'pass';
$server="localhost";//or server IP
$database="database";
$conn = odbc_connect("Driver={SQL Server};Server=$server;Database=$database;", $user, $password);
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
回答1:
I use PDO_ODBC Method:
1- Install ODBC on server that has wamp and enable PHP_PDO_ODBC extension on your wamp
2- Use this code that supports UTF-8:
try{
$hostname = "IP";
$dbname = "database";
$username = "username";
$pw = "password";
$pdo = new PDO ("odbc:Driver={SQL Server Native Client 10.0};Server=$hostname;Database=$dbname; Uid=$username;Pwd=$pw;");
} catch (PDOException $e) {
echo "Failed : " . $e->getMessage() . "\n";
exit;
}
$query = $pdo->prepare("select field_name from table");
$query->execute();
for($i=0; $row = $query->fetch(); $i++){
echo iconv("CP1256","UTF-8", $row['field_name'])."<br>";
}
3- replace these Items with yours:
IP-database-username-password-field_name-table
4- sometimes you need use "SQL SERVER" instead of "SQL Server Native Client 10.0" and sometimes you need use "IP,port" instead of "IP" and sometimes you need use "ISO-8859-6" instead of "CP1256".
回答2:
From the PHP manual: http://php.net/manual/en/pdo.construct.php
Example #1 Create a PDO instance via driver invocation
<?php
/* Connect to a SQL Server database using driver invocation */
$dsn = "sqlsrv:Server=12345abcde.database.windows.net;Database=testdb", "UserName@12345abcde", "Password";
try {
$dbh = new PDO($dsn);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
Just change the HOST ip to the IP and port of your mysql server.
来源:https://stackoverflow.com/questions/41146103/connection-between-php-and-sql-server-using-wamp-new-approaches