How to create connection in PHP?

The mysqli_connect() function is used to create a connection in PHP.

resource mysqli_connect (server, username, password)

To create a connection in PHP, typically you would use the PDO (PHP Data Objects) or MySQLi extension. Here’s a basic example of how to create a database connection using PDO:

php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
?>

And here’s an example using MySQLi:

php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

In both examples:

  • $servername should be set to the name of the server where your database is hosted (usually “localhost” if it’s on the same server as your PHP script).
  • $username and $password should be set to the credentials required to access your database.
  • $dbname should be set to the name of the database you want to connect to.

Remember to replace “username”, “password”, and “database” with your actual database credentials. Additionally, error handling is implemented to catch any connection errors that may occur.