@herminia_bruen
To connect to a SQL Server database using PHP, you can use the following steps:
- Install the necessary PHP extensions: Make sure the required PHP extensions for SQL Server are installed and enabled. The two popular extensions are sqlsrv and pdo_sqlsrv. You can install them using the package manager or by enabling them in the php.ini file.
- Establish a database connection: Use the sqlsrv_connect function or the PHP Data Objects (PDO) to establish a connection to the SQL Server database.
Using sqlsrv extension:
$serverName = "localhost";
$connectionOptions = array(
"Database" => "your_database_name",
"Uid" => "your_username",
"PWD" => "your_password"
);
$conn = sqlsrv_connect($serverName, $connectionOptions);
if ($conn === false) {
die(print_r(sqlsrv_errors(), true));
}
Using PDO extension:
$serverName = "localhost";
$databaseName = "your_database_name";
$username = "your_username";
$password = "your_password";
try {
$conn = new PDO("sqlsrv:Server=$serverName;Database=$databaseName", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("Connection failed: " . $e->getMessage());
}
- Execute SQL queries: Once the database connection is established, you can execute SQL queries using either sqlsrv_query or PDO's prepare and execute methods.
Example using sqlsrv extension:
$query = "SELECT * FROM your_table_name";
$stmt = sqlsrv_query($conn, $query);
if ($stmt === false) {
die(print_r(sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
echo $row['column_name'] . "";
}
sqlsrv_free_stmt($stmt);
Example using PDO extension:
$query = "SELECT * FROM your_table_name";
$stmt = $conn->prepare($query);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo $row['column_name'] . "";
}
Remember to replace 'localhost'
, 'your_database_name'
, 'your_username'
, and 'your_password'
with your actual server, database, username, and password details.