Gerner Christensen
Gerner Christensen

Reputation: 43

How to connect to a database using PHP's include

I'm trying to connect to a database using a config file that is a part of my Joomla website.
My config file looks like:

<?php
class JConfig {
    public $dbtype = 'mysqli';
    public $host = 'localhost';
    public $user = 'xxxx';
    public $password = 'xxxx';
    public $db = 'xxxx';
    public $dbprefix = 'xxxx_';
}

Below is the page that includes the configuration file:

<?php
include("configuration.php");

// Create connection
$conn = mysqli_connect($host, $user, $password, $db);

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

$sql = "SELECT id, navn, email FROM XXXX";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
    // Output data of each row
    while ($row = mysqli_fetch_assoc($result)) {
        echo "id: " . $row["id"]. " - Name: " . $row["navn"]. " " . $row["email"]. "<br>";
    }
} else {
    echo "0 results";
}

mysqli_close($conn);

However, I cannot connect to the database as I get the following error message:

Connection failed: Access denied for user ''@'localhost' (using password: NO)

I think the issue might be because the config file has public in front of all the variables.


Question: How can I get around keeping the variables public, since the Joomla script needs them, but avoid the error?

Upvotes: 2

Views: 3383

Answers (1)

ArtisticPhoenix
ArtisticPhoenix

Reputation: 21681

Assuming the path is correct, do this instead:

require_once "configuration.php";

$Conf = new JConfig;

// Create connection
$conn = mysqli_connect($Conf->host, $Conf->user, $Conf->password, $Conf->db);

In simple terms the config file contains an class named JConfig, so you must instantiate that class and access it's public properties.

other stuff

Use require not include, as this config is needed for the rest of this script to work and include will just ignore missing files. Require will produce an error, and let you know what is wrong when the file is missing/no found. Further, use require once because you cannot redefine the same class multiple times.

PS. you don't need the () on include/require, and the same is true for construct with no arguments... (I'm lazy so I don't like to type those things out)

Enjoy!

Upvotes: 2

Related Questions