如何使用 REST API 从表中获取数据
我想使用 Slim 框架在 php 中制作 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 为 5 的学校详细信息的函数。所以请建议我如何创建一个函数,以便我可以访问学校拘留所,网址中给出的 ID 像这样
192.168.1.126/schools/:5
I want to make rest API in php using Slim framework.
I have created a function to get all entries of my table like this:-
<?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);
}
});
?>
Now i want to make a function which returns detail of school which id is 5. so please suggest me how can make a function so i can access school detain which id is given in url like this
192.168.1.126/schools/:5
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我在您的其他问题上发布了一些类似的信息。我强烈建议您对数据库内容使用对象关系映射。这让我的生活变得超级轻松。听起来您已经了解 SQL,所以您应该能够轻松掌握它。文档很扎实。查看这段代码是否可以满足您的要求。 Idiorm/Paris
一旦你有了 GET、POST、PUT、DELETE 路由器,你只需使用Paris 的简单功能,您不必担心长且容易出错的查询字符串。 :-)
I posted some similar information on your other question. I highly recommend using object relational mapping for your DB stuff. It made my life super easy. Sounds like you already know SQL so you should be able to pick it up in a breeze. The documentation is solid. Check out this code that does what you want. Idiorm/Paris
Once you have your GET, POST, PUT, DELETE routers in place, you just use the easy features of Paris and you don't have to worry about long error prone query strings. :-)
我通过使用一些教程解决了我的问题。
这是我的解决方案:
我希望这对未来的读者有所帮助。
I resolved my problem by using some tutorials.
This is my solution:
I hope this will help future readers.