create sql server connection in php

To establish a connection between PHP and SQL Server, we can use PDO (PHP Data Objects) library. Follow the below steps:

  1. Install the PDO driver for SQL Server (if not already installed)
main.php
// For Ubuntu
sudo apt-get install php7.0-sybase

// For CentOS
sudo yum install php70w-sybase
95 chars
6 lines
  1. Create a new PDO instance by specifying the server name, database name, username and password.
main.php
$serverName = "localhost\SQLEXPRESS"; //serverName\instanceName
$connectionOptions = array(
    "Database" => "dbName",
    "Uid" => "username",
    "PWD" => "password"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);
229 chars
8 lines
  1. Write SQL queries and execute them using the connection object.
main.php
if ($conn) {
    $sql = "SELECT * FROM tableName";
    $stmt = sqlsrv_query($conn, $sql);
    if ($stmt === false) {
        die(print_r(sqlsrv_errors(), true));
    }

    while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
        echo $row['columnName'] . "\n";
    }

    sqlsrv_free_stmt($stmt);
} else {
    echo "Connection could not be established.<br />";
    die(print_r(sqlsrv_errors(), true));
}
419 chars
17 lines

Note: Remember to handle exceptions and errors while establishing the connection and executing queries.

gistlibby LogSnag