Morgane Flamant Morgane Flamant - 3 years ago 107
MySQL Question

Slim API, doesn't work after connection

I'm trying to make an API. I've follow a tutorial in OpenClassRoom to make request with MySQL, and I want an API with Slim v3.2.
So I receive the answer of the connexion, but when I want to recover data from a get I have a "Slim Application Error" And I don't know what to do with that.
I'm using MAMP instead of "php -S localhost:8080 -t public public/index.php " because I have the good connection with my database.
I show you my API:

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

require '/Users/kravennagen/Downloads/Api/api/racehistory/vendor/autoload.php';

$app = new \Slim\App();
echo "hello";
$bdd = new PDO('mysql:host=localhost;dbname=racehistory;charset=utf8', 'root', 'root', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
echo "connexion...";
catch(Exception $e){
die('Erreur connexion BDD:' . $e->getMessage());
echo "avant le get";
$app->get('/', function(){
$reponse = $bdd->query('SELECT * FROM user');
while($data = $reponse->fetch()){
echo $data['mail'];
echo $data['password'];
$app->get('/connexion/{identifiant}/{password}', function($login, $pass){
$reponseMail = $bdd->query('SELECT mail FROM user');
$reponsePass = $bdd->query('SELECT password FROM user');
echo "test1";
While($donnees = $reponseMail->fetch() && $donnees = $reponsePass->fetch()){
if($donnees['mail'] == $login && $donnees['password'] == $pass){
echo "true";
//return true;
echo "false";
//return false;

$app->get("/register/{identifiant}/{password}", function($login, $pass){
$add = 'INSERT INTO user(mail, password) VALUES ($login, $pass)';

if(!preg_match("#^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$#", $login))
$errors['mail'] = 'adresse mail non valide';

else if (!preg_match("#^(?=.*[A-Z])(?=.*[a-zA-Z])(?=.*\d)([\w]{8,15})$#", $pass))
$errors['password'] = "le mot de passe n'est pas conforme(majuscule au debut, de 8 a 15 caractères)";

else if($bdd->exec($add) === false){
echo "User bien ajouté la base de donnée";

Answer Source

You have to inject your $bdd connection object to the route by using "use":

$app->get('/', function() use ($bdd) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download