0

Code in Connection.php

<?php

    class Connection{

        private $conn;

        function connect(){
            include_once dirname(__FILE__) . '/Constants.php';
            $this->conn = new mysqli($DB_HOST, $DB_USER, $DB_PASSWORD, $DB_NAME, $DB_PORT);

            if (mysqli_connect_errno()){
                echo "Failed to connect " . mysqli_connect_error();
                return null;
            }

            return $this->conn;
        }
    }

Using direct php code would work:

<?php

    require __DIR__ . '/../includes/Connection.php';

    $db = new Connection;
    if ($db->connect() != null) {
        echo 'Connection successful';
    }
?> 

However, following code would generate '500 Internal Error'

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../includes/Connection.php';

$app = AppFactory::create();

$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");

    $db = new Connection;
    if ($db->connect() != null) {
        echo 'Connection successful';
    }

    return $response;
});

$app->run();

Log Stacktrace

PHP Fatal error:  Uncaught Error: Class 'mysqli' not found in C:\xampp\htdocs\EctApi\includes\Connection.php:9

php.ini has enabled the extension for mysqli. Now I am totally confused! Please help.

  • Try using `\mysqli` – Dharman Apr 25 '20 at 23:45
  • Please never check for mysqli connections manually. Please read: [Should we ever check for mysqli_connect() errors manually?](https://stackoverflow.com/q/58808332/1839439) – Dharman Apr 25 '20 at 23:46
  • 2
    Check with `phpinfo()` if mysqli is enabled. – Dharman Apr 25 '20 at 23:47
  • If you are using slim, I do not recommend using mysqli. You really should be using PDO. Also, it's generally better to put the connection in the container. – Dharman Apr 25 '20 at 23:49
  • finally I figured it out, I need to declare something like $app->setBasePath("/EctApi/public"); unbelievably stupid. – Xuanfei Apr 26 '20 at 18:39
  • A tip: The `/public` path should not be part of the baseBath in Slim. If the setup is "correct" then it should be only: `$app->setBasePath("/EctApi")`. – odan Apr 27 '20 at 08:03

0 Answers0