Clay Campbell
Clay Campbell

Reputation: 168

Class not appearing after requiring it in PHP

I am trying to connect my Cloud MySQL in GCloud to my App in App Engine.

This is the code for the class which should connect to the database. The file is connect_db.php:

<?php
namespace Google\Cloud\Samples\CloudSQL\MySQL;

use PDO;
use PDOException;
use RuntimeException;
use TypeError;

class DatabaseUnix
{
    public static function initUnixDatabaseConnection(): PDO
    {
            $username = getenv('XXXX'); // e.g. 'your_db_user'
            $password = getenv('XXXX'); // e.g. 'your_db_password'
            $dbName = getenv('XXXX'); // e.g. 'your_db_name'
            $instanceUnixSocket = getenv('XXXX'); // e.g. '/cloudsql/project:region:instance'

            // Connect using UNIX sockets
            $dsn = sprintf(
                'mysql:dbname=%s;unix_socket=%s',
                $dbName,
                $instanceUnixSocket
            );

            // Connect to the database.
            $conn = new PDO(
                $dsn,
                $username,
                $password
            );

    return $conn;
    }

}
?>

Here is my second file code, all.php , in the same directory:

<?php
use Google\Cloud\Samples\CloudSQL\MySQL;
require $_SERVER["DOCUMENT_ROOT"]."/af/connect_db.php";

$db = new DatabaseUnix();

$sql = "SELECT * FROM users";

$users = [];
$result = $db->query($sql);
while ($row = $result->fetch_assoc()) {
    $users[] = $row;  
}

#a bunch of html
?>

I keep on getting the following error:

Fatal error: Uncaught Error: Class 'DatabaseUnix' not found in /workspace/af/all.php:6 Stack trace: #0 /workspace/index.php(15): require() #1 {main} thrown in /workspace/af/all.php on line 6

#this is the line of code $db = new DatabaseUnix(); in all.php

Thank you!

Upvotes: 1

Views: 65

Answers (1)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146460

Your use statement is incomplete:

use Google\Cloud\Samples\CloudSQL\MySQL;

You cannot alias a complete namespace, you need to specify the concrete class. In this case:

use Google\Cloud\Samples\CloudSQL\MySQL\DatabaseUnix;

Alternatively, you could also use the fully-qualified class name (but creating an alias with use is normally handier):

$db = new \Google\Cloud\Samples\CloudSQL\MySQL\DatabaseUnix();

Upvotes: 1

Related Questions