0

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'); 
}
3
  • $dbHost = "*static ip of wordpress site*"; - shouldn't that be localhost?
    – Rup
    Commented Apr 18, 2021 at 23:14
  • But this sounds like it's a configuration problem on the host. Can you SSH in and work out how to connect to the database on localhost?
    – Rup
    Commented Apr 18, 2021 at 23:16
  • That's it! It works with localhost. Many thanks for your help! you can post it as answer if you like :) Commented Apr 19, 2021 at 20:45

1 Answer 1

0
//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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.