Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The method for establishing a connection to your website's database using PHP is to use the mysqli or PDO extension. Here are the steps to connect to the database:

  1. Create a database on your webhosting server.
  2. Open a PHP file inside your website's directory and set up a connection to the database by creating a new instance of either the mysqli or PDO class.
  3. Use the connection object to execute SQL queries and access the data in your database.

Example code for connecting using mysqli:

$host = "localhost";
$user = "username";
$password = "password";
$database = "dbname";

// Create connection
$conn = new mysqli($host, $user, $password, $database);

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

Example code for connecting using PDO:

$host = "localhost";
$user = "username";
$password = "password";
$database = "dbname";

// Set DSN
$dsn = "mysql:host=$host;dbname=$database";

// Create a PDO instance
$conn = new PDO($dsn, $user, $password);

// Set PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);