To connect to a SQL server database using PHP, you can use the mysqli extension. Here’s an example code that demonstrates the connection:
<?php
$servername = "localhost"; // Change this to your SQL server hostname
$username = "root"; // Change this to your database username
$password = "password"; // Change this to your database password
$dbname = "mydatabase"; // Change this to your database name
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
// Perform your SQL queries...
// Close connection
$conn->close();
?>
In the code above, you need to replace “localhost” with your SQL server hostname, “root” with your database username, “password” with your database password, and “mydatabase” with the name of your database.
After connecting to the database, you can perform SQL queries using the $conn
object. Make sure to handle any errors that may occur during the connection or query execution.
Finally, the connection is closed using the $conn->close()
method to free up resources.
Note: It’s recommended to store the database credentials in a separate configuration file and include it in your code instead of hardcoding them directly in the code for security reasons.