Thuta Learning
AdvancedProgrammingbeginner

Connect to Database

Relax. We'll talk through this in plain words — no textbook voice.

PHP needs a connection to talk to the database. On local XAMPP, the host is usually localhost, the user is root, and the password is typically empty. In production, though, secure credentials should be stored in an environment/config file.

php
<?php
$host = "localhost";
$user = "root";
$password = "";
$database = "thutatech_demo";

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

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

echo "Database connected successfully.";
?>
You should see
Database connected successfully.

Easy traps

  • If you try to connect without having created the database first, you may get an Unknown database error.
Connect to Database | Thuta Learning