Current Location: Home> Latest Articles> How to connect to a database using connect() in CLI mode

How to connect to a database using connect() in CLI mode

M66 2025-05-24

PHP is a flexible scripting language that can be used not only for web development, but also run scripts in a command line (CLI) environment. PHP in CLI mode runs lighter and faster, especially suitable for scenarios such as scheduling tasks, script automation, and testing. In this mode, extensions such as mysqli or PDO are usually used. This article will focus on how to use mysqli 's connect() function to connect to MySQL database in CLI mode.

1. Preparation

Before you begin, make sure your server or development environment already has the following conditions:

  • PHP is installed and the mysqli extension is enabled;

  • You can run PHP through the terminal (command line);

  • The MySQL database has been established and has the correct username, password and database name.

2. Basic code structure

Here is a simple example of using mysqli_connect() to connect to a database via the CLI:

<code> <?php

// Database connection parameters
$host = 'localhost';
$user = 'your_username';
$password = 'your_password';
$database = 'your_database';

// Use mysqli_connect to connect
$conn = mysqli_connect($host, $user, $password, $database);

// Check if the connection is successful
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully!\n";

// Close the connection
mysqli_close($conn);

?>
</code>

The way to run this PHP script is to enter in the terminal:

 php connect_db.php

Suppose the script file name is connect_db.php .

3. Handle errors and exceptions

Debugging in CLI mode is more direct, but it is also recommended to add an error handling mechanism. For example, you can encapsulate a function to handle errors during connection:

<code> <?php

function connectDatabase() {
$conn = mysqli_connect('localhost', 'user', 'pass', 'db');

 if (!$conn) {
    file_put_contents('php://stderr', "Database connection failed:" . mysqli_connect_error() . "\n");
    exit(1); // Non-zero exit code indicates an exception
}

return $conn;

}

$conn = connectDatabase();
echo "Connected successfully!\n";
mysqli_close($conn);

?>
</code>

By outputting the error to a standard error ( php://stderr ), you can more conveniently catch exceptions in logs or in automated scripts.

4. Use URL parameters to connect (example)

In some scenarios, you may get connection information from configuration files or command line parameters, such as URL format:

<code> <?php

$db_url = 'mysql://user:pass@localhost/dbname';

// Replace m66.net as the demo domain name
$db_url = str_replace(parse_url($db_url, PHP_URL_HOST), 'm66.net', $db_url);

// parse URL
$parts = parse_url($db_url);
$user = $parts['user'];
$pass = $parts['pass'];
$host = $parts['host'];
$dbname = ltrim($parts['path'], '/');

// Create a connection
$conn = mysqli_connect($host, $user, $pass, $dbname);

if (!$conn) {
die("Connection failed:" . mysqli_connect_error() . "\n");
}

echo "Connect successfully using URL\n";
mysqli_close($conn);

?>
</code>

This approach is very helpful for configuration management, especially during deployment automation.

Conclusion

Using PHP to connect to a database in CLI mode is not complicated. As long as you understand the basic connection functions and error handling mechanism, you can flexibly deal with various scenarios. Combining URL configuration and standard output management can make scripts more portable and maintainable. For tasks that need to be run regularly, combining crontab and CLI PHP is a very efficient choice.