2016-10-21 43 views
0

我正在嘗試製作一個API。我在OpenClassRoom中遵循一個教程來向MySQL提出請求,並且我想要一個帶Slim v3.2的API。 所以我收到connexion的答案,但是當我想從一個get中恢復數據時,我有一個「Slim Application Error」,我不知道該怎麼做。 我使用MAMP而不是「php -S localhost:8080 -t public public/index.php」,因爲我與我的數據庫有良好的聯繫。 我告訴你我的API:使用 「使用」Slim 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._-][email protected][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(); 
?> 

回答

2

你必須注入你的$ BDD連接對象的路線:

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

謝謝!!!!有用 ! –

+0

不客氣:-) –