Search code examples
phpmysqlixampp

Connection to database using XAMPP


It is my first time using PHP. I am using XAMPP on a mac.

MySQL, Apache, and localhost:8080 are all working right now. I created this file called test.php and saved it inside lampp/htdocs:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Connection</title>
</head>
<body>

<?php
  $servername = "localhost:8080";
  $username = "root";
  $password = "root";

  // Create connection
  $conn = mysqli_connect($servername, $username, $password);

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



</body>
</html>

However, when I go to localhose:8080/test.php a blank page opens but nothing shows up


Solution

  • Port 8080 is for your web server. Your MySQL server listens by default on port 3306. You can check in your XAMPP settings if the port is different, but it should be 3306. This means that you can omit the port number.

    To connect to the database using mysqli you only need 3 lines of code:

    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
    $mysqli = new mysqli('localhost', 'user', 'pass', 'db_name', 3306); // you can omit the last argument
    $mysqli->set_charset('utf8mb4'); // always set the charset