Решил написать rest api для своего приложения. Выкидывает ошибку:
Type: Error
Message: Call to a member function prepare() on null
File: C:\wamp64\www\usatu\include\DbOperation.php
Line: 15
Как я понял prepare возвращает Null, т.е проблемы с базой данной?
<?php
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
//including the required files
require_once '../include/DbOperation.php';
require '.././libs/Slim/vendor/autoload.php';
$app = new \Slim\App([
'settings'=>[
'displayErrorDetails'=>true
]
]);
/*
* URL: http://localhost/usatu/v1/allGroups
*/
$app->get('/allGroups', function (Request $request, Response $response){
$db = new DbOperation();
$groups = $db->getAllStudents();
$response_data = array();
$response_data['error'] = false;
$response_data['groupsStudents'] = $groups;
$response->write(json_encode($response_data));
return $response
->withHeader('Content-type', 'application/json')
->withStatus(200);
});
$app->run(true);
Класс операций bd
class DbOperation
{
private $con;
function __construct()
{
require_once dirname(__FILE__) . '/DbConnect.php';
$db = new DbConnect();
$this->con = $db->connect();
}
//Method to fetch all students from database
public function getAllStudents(){
$stmt = $this->con->prepare("SELECT * FROM class");
$stmt->execute();
$students = $stmt->get_result();
$stmt->close();
return $students;
}
Класс DbConnect
class DbConnect
{
private $con;
function __construct()
{
}
function connect()
{
include_once dirname(__FILE__) . '/Constants.php';
$this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
return $this->con;
}
}
}
Полный Trace
#0 C:\wamp64\www\usatu\v1\index.php(22): DbOperation->getAllStudents()
#1 [internal function]: Closure->{closure}(Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#2 C:\wamp64\www\usatu\libs\Slim\vendor\slim\slim\Slim\Handlers\Strategies\RequestResponse.php(41): call_user_func(Object(Closure), Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#3 C:\wamp64\www\usatu\libs\Slim\vendor\slim\slim\Slim\Route.php(356): Slim\Handlers\Strategies\RequestResponse->__invoke(Object(Closure), Object(Slim\Http\Request), Object(Slim\Http\Response), Array)
#4 C:\wamp64\www\usatu\libs\Slim\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(117): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#5 C:\wamp64\www\usatu\libs\Slim\vendor\slim\slim\Slim\Route.php(334): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#6 C:\wamp64\www\usatu\libs\Slim\vendor\slim\slim\Slim\App.php(516): Slim\Route->run(Object(Slim\Http\Request), Object(Slim\Http\Response))
#7 C:\wamp64\www\usatu\libs\Slim\vendor\slim\slim\Slim\MiddlewareAwareTrait.php(117): Slim\App->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#8 C:\wamp64\www\usatu\libs\Slim\vendor\slim\slim\Slim\App.php(407): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#9 C:\wamp64\www\usatu\libs\Slim\vendor\slim\slim\Slim\App.php(315): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))
#10 C:\wamp64\www\usatu\v1\index.php(33): Slim\App->run()
#11 {main}
Update:
$app->get('/allGroups', function (Request $request, Response $response) {
$db = new DbConnect();
try {
$db = $db->connect();
$groups = $db->query("SELECT * FROM class")->fetchAll(PDO::FETCH_OBJ);
return $response
->withStatus(200)
->withHeader("Content-Type", 'application/json')
->withJson($groups);
} catch (PDOException $e) {
return $response->withJson(
array(
"error" => array(
"text" => $e->getMessage(),
"code" => $e->getCode()
)
)
);
}
$db = null;
});
class DbConnect
{
private $dbhost = "localhost";
private $dbuser = "root";
private $dbpass = "";
private $dbname= "schedule_usatu";
public function connect()
{
$mysql_connection = "mysql:host=$this->dbhost;dbname=$this->dbname;charset=utf-8";
$connection = new PDO($mysql_connection, $this->dbuser, $this->dbpass);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $connection;
}
}
Виртуальный выделенный сервер (VDS) становится отличным выбором
проблема в следующемПри генерации массива в цикле while получаю ошибку 503, в массив записывается около 100 000 строк
Существует серверная часть на PHP и клиент на C#Мне нужно сначала провести "верификацию", потом основной запрос, всё в рамках одного запроса,...