Unable to connect to database with wp cli

Hello!

I want to modify the database from the wp cli command.
However, I get an error message.

$ wp db tables --allow-root
Error: Error establishing a database connection.

$ wp db check

Info: Using unique option prefix 'pass' is error-prone and can break in the future. Please use the full name 'password' instead.

mysqlcheck: Got error: 2002: Can't connect to local MySQL server through socket '/run/mysqld/mysqld.sock' (2) when trying to connect

I have this setup.

file: wp-cli.yml
path: web/wp
require:
  - config/cli-bootstrap.php
server:
  docroot: web 

file: config/cli-bootstrap.php
<?php
use function Env\env;

/**
 * Directory containing all of the site's files
 *
 * @var string
 */
$root_dir = dirname(__DIR__);

/**
 * Use Dotenv to set required environment variables and load .env file in root
 */
if (file_exists($root_dir . '/.env')) {
    require_once($root_dir . '/vendor/autoload.php');
    $dotenv = Dotenv\Dotenv::createImmutable($root_dir);
    $dotenv->load();
    $dotenv->required(['WP_HOME', 'WP_SITEURL']);
    if (!env('DATABASE_URL')) {
        $dotenv->required(['DB_NAME', 'DB_USER', 'DB_PASSWORD']);
    }
}

file: .env
DB_NAME='wordpress'
DB_USER='root'
DB_PASSWORD='password'
DB_HOST='localhost'
DB_PREFIX='wp_'

WP_ENV='development'
WP_HOME='http://localhost'
WP_SITEURL="${WP_HOME}/wp"

I confirmed that I could connect to the database.

# mysql -uroot -ppassword -hlocalhost wordpress
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MariaDB monitor. Commands end with ; or \g.
Your MySQL connection id is 20
Server version: 5.7.35 MySQL Community Server (GPL)
Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MySQL [wordpress]>

Do I need any other settings?

The WP CLI configuration file (wp-cli.yml) must be used by the connecting client_ (on your workstation).
The cwd must be where that file is so wp can find and use it for a remote connection.
Otherwise you would have to connect directly to server (SSH) and run wp from there,
but that would be overcomplicated and neglect the remote feature of wp.

1 Like

See also: https://roots.io/guides/using-wp-cli-aliases/

1 Like

thanks for the awesome information.

1 Like

This topic was automatically closed after 42 days. New replies are no longer allowed.