AWS Lightsail Wordpress - connect to database on instance using mysqli

I have a wordpress website hosted on AWS Lightsail. On that website, I would like to use a shortcode to retrieve data from a database using mysqli. However, everytime the script that connects to the database is executed, I receive a connection error. The database is on the same AWS Lightsail instance. I was wondering if I need to establish an SSH-tunnel because this is also needed if I connect to phpmyadmin. But since the script is executed on the server itself this does not really makes sense in my understanding. I have used the exact same code on a local host and it worked perfectly fine. What am I missing here?

//Params to connect to a database
$dbHost = *static ip of wordpress site*;
$dbUser = root;
$dbPassword = *password*;
$dbName = *database name*;


mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
try {
  $db = new mysqli($dbHost, $dbUser, $dbPassword, $dbName);
  $db-set_charset(utf8mb4);
} catch(Exception $e) {
  error_log($e-getMessage());
  exit('Error connecting to database'); 
}

Topic ssh mysql php Wordpress

Category Web


//Params to connect to a database
$dbHost = "*static ip of wordpress site*";

This should be $dbHost = "localhost"; instead, or "127.0.0.1" (or even "::1").

localhost uses a separate virtual network interface that makes sure traffic between services on your Linux VM doesn't leave the VM In general it's safer to use localhost rather than other IPs that belong to host interfaces because

  • you'll avoid any problems with firewalls that might be configured on the host
  • ditto in an AWS environment you'll avoid any security group / VPC filters, if e.g. you were using the public facing IP as your host rather than the internal IP address on the virtual private cloud which is different
  • mysql logins can be filtered by the hosts they're allowed to connect from, and if your root user may be restricted to localhost logins at the database level.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.