Slim + PHP + MySQLi:异常:标识符 "select * from users" 未定义

Slim + PHP + MySQLi : Exception: Identifier "select * from users" is not defined

这是我的 db_david.php 文件:

<?php

    $app->get('/db', function() {
        require_once 'connection.php';

        $query = "select * from users";
        $result = $mysqli->query($query);

        while($row = $this->$query->fetch_aasoc()){
            $data[] = $row;
        }

        echo json_encode($data);
    });
?>

这是connection.php的内容:

  <?php
        $host = "localhost";
        $user = "root";
        $pass = ".....";
        $db_name = "....";

        $mysqli = new mysqli($host, $user, $pass, $db_name);
    ?>

这是index.php的内容:

<?php

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

require '../libs/vendor/autoload.php';

$app = new \Slim\App(['settings' => ['displayErrorDetails' => true]]);

require_once '../include/db_david.php'; 
$app->run();


?>

我遇到 Slim 应用程序错误。由于以下错误,应用程序无法 运行:

Type: Slim\Exception\ContainerValueNotFoundException
Message: Identifier "select * from users" is not defined.
File: /opt/lampp/htdocs/task_manager/libs/vendor/slim/slim/Slim/Container.php
Line: 120

乍一看,查询有错字属性

$this->$query->fetch_assoc()){ 

应该是

$this->query->fetch_assoc()){

您获取数据的方式完全错误...

$query = "select * from users";
$result = $mysqli->query($query);

while($row = $result->fetch_assoc()){   // Fetch the value from the result
    $data[] = $row;
}

另请注意 fetch_aasoc()

的错误输入

我建议另一种方法,利用 Slim 的依赖容器。

我们的想法是向容器注册一个函数,该函数将 return 连接对象的实例添加到您的应用程序。

下面是一个简单的例子

<?php

use Slim\App;
use Slim\Container;
use Slim\Http\Request;
use Slim\Http\Response;

require_once("../vendor/autoload.php");

// create your slim application with a dependency container
$app = new App( new Container );

// get the container
$container = $app->getContainer();

// add a function that returns instance of dependency
$container['database'] = function($container) {

    return new \mysqli('localhost', 'root', '', 'yourdbname');

};

$app->get('/', function(Request $req, Response $res, $args){

    $query = $this->database->query("select * from table");
    // do something with the result

});

这种方法的一个巨大好处是您不需要在路由中需要更多文件。想象一下,如果您移动那个 connection.php 文件,那么您需要更新很多代码,使用这种方法您只需要弄乱工厂。

强烈建议您阅读以下内容https://www.slimframework.com/docs/v3/concepts/di.html