Skip to content
PHP Logo

In the context of a MySQL class, is it safer to pass connection credentials as parameters or use constants for storing them?

It is generally safer to pass connection credentials as parameters rather than storing them as constants in your code. This is because constants are stored in plain text within the code, making them potentially vulnerable to exposure if the code is compromised. Passing credentials as parameters allows for greater flexibility and security, as they are not hard-coded into the application.

php
// Using parameters to pass connection credentials
function connectToDatabase($host, $username, $password, $database) {
    $conn = new mysqli($host, $username, $password, $database);

    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    return $conn;
}

// Call the function with the appropriate credentials
$host = "localhost";
$username = "root";
$password = "password";
$database = "my_database";

$connection = connectToDatabase($host, $username, $password, $database);