Slim API,连接后不起作用

时间:2016-10-21 15:37:09

标签: mysql api pdo get slim

我正在尝试制作API。我已经按照OpenClassRoom中的教程向MySQL发出请求,我想要一个带有Slim v3.2的API。 所以我收到了连接的答案,但是当我想从get中恢复数据时,我有一个" Slim Application Error"而且我不知道该怎么做。 我使用的是MAMP而不是" php -S localhost:8080 -t public public / index.php"因为我与我的数据库有良好的联系。 我告诉你我的API:

<?php
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";
try{
    $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'];
  }
  $reponse->closeCursor();
});
$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;
        }
        else{
      echo "false";
            //return false;
        }
    }
$reponsePass->closeCursor();
$reponseMail->closeCursor();
});

$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 "ERREUR INSERTION";
    }
    else{
        echo "User bien ajouté la base de donnée";
    }
});
$app->run();
?>

1 个答案:

答案 0 :(得分:3)

您必须使用“use”将

$app->get('/', function() use ($bdd) {