如何使用REST API从表中获取数据

问题描述:

我想在使用Slim框架的PHP中制作其余的API。如何使用REST API从表中获取数据

我创建了一个功能,让我的表像这样的所有条目: -

<?php 

    header('Content-type: application/json'); 

    // Include the Slim library 
    require 'Slim/Slim.php'; 

    // Instantiate the Slim class 
    $app = new Slim(); 

    // Create a GET-based route 
    $app->get('/', function() { 
    echo "Pericent is working on Campus Concierge..."; 
    }); 

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

    $sql = "SELECT * from school"; 

    $result = mysql_query($sql) or die ("Query error: " . mysql_error()); 

    $records = array(); 
    if (mysql_num_rows($result)==0) 
    { 

     echo '('.'['.json_encode(array('id' => 0)).']'.')'; 
    } 
    else 
    { 
     while($row = mysql_fetch_assoc($result)) 
     { 

      $records[] = $row; 
     } 

      echo json_encode($records); 
    } 

}); 
?> 

现在我想让它返回学校,id为的详细功能。所以,请建议我怎样才能使一个功能,所以我可以访问学校扣留其ID在URL中给出这样

192.168.1.126/schools/:5 

我用一些教程解决我的问题。

这是我的解决方案:

$app->get('/schools/:id', function ($id) { 

// Retrieve game associated with an ID of $id 
$sql = "SELECT * from school where schoolId='$id'"; 

$result = mysql_query($sql) or die ("Query error: " . mysql_error()); 

$records = array(); 
if (mysql_num_rows($result)==0) 
{ 

    echo '('.'['.json_encode(array('id' => 0)).']'.')'; 
} 
else 
{ 
    while($row = mysql_fetch_assoc($result)) 
    { 

    $records[] = $row; 
    } 

    echo json_encode($records); 
} 
}); 

我希望这将有助于未来的读者。

我在您的其他question上发布了一些类似的信息。我强烈建议使用对象关系映射来处理数据库内容。它让我的生活变得非常简单。听起来像你已经知道SQL,所以你应该能够轻松地拿起它。该文件是可靠的。看看你想要的代码。 Idiorm/Paris

class School extends Model {} 

$app->get('/school/:id', function($id) use ($app) { 

    $school = Model::factory('School')->find_one($id); // Paris: row with $id 
    $schoolAry = $school->as_array('id', 'name', 'zip', 'numStudents'); 

    $response = $app->response(); // Slim Response object at work 
    $response['Content-Type'] = 'application/json'; 

    echo json_encode($schoolAry); // Output 
}); 

一旦你有你的GET,POST,PUT,DELETE路由器的地方,你只需要使用巴黎方便的特点,你不必担心长容易出错的查询字符串。 :-)