我正在尝试构建一个简单的api,它只是从MYSQL服务器返回JSON。我想实现你可以用id搜索的可能性。这是我的代码:
// Load Slim
require 'vendor/autoload.php';
$configuration = [
'settings' => [
'displayErrorDetails' => true,
],
];
$c = new \Slim\Container($configuration);
$app = new \Slim\App($c);
$app->get('/leerlingen','ll_posts'); //Get all "leerlingen" posts.
$app->get('/docenten', 'do_posts'); //Get all "docenten" posts.
$app->get('/ouders', 'ou_posts'); //Get all "ouders" posts.
$app->get('/bedrijven', 'be_posts'); //Get all bedrijven posts.
$app->get('/ll/search/:id', 'll_search'); //Get info for certain id.
function ll_posts() {
$sql = "SELECT * FROM leerlingen WHERE approved = 'true'";
try{
$db = getConnection();
$stmt = $db->query($sql);
$posts = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($posts);
} catch(PDOException $e){
echo '{"error":{"text":'.$e->getMessage().'}}';
}
}
function do_posts() {
$sql = "SELECT * FROM docenten WHERE approved = 'true'";
try{
$db = getConnection();
$stmt = $db->query($sql);
$posts = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($posts);
} catch(PDOException $e){
echo '{"error":{"text":'.$e->getMessage().'}}';
}
}
function ou_posts() {
$sql = "SELECT * FROM ouders WHERE approved = 'true'";
try{
$db = getConnection();
$stmt = $db->query($sql);
$posts = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($posts);
} catch(PDOException $e){
echo '{"error":{"text":'.$e->getMessage().'}}';
}
}
function be_posts() {
$sql = "SELECT * FROM bedrijven WHERE approved = 'true'";
try{
$db = getConnection();
$stmt = $db->query($sql);
$posts = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($posts);
} catch(PDOException $e){
echo '{"error":{"text":'.$e->getMessage().'}}';
}
}
function ll_search($id) {
$sql = "SELECT * FROM leerlingen WHERE id = :id";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("id", $id);
$stmt->execute();
$names = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo json_encode($names);
} catch(PDOException $e) {
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
$app->run();
function getConnection(){
$dbPost = "localhost";
$dbUser = "a1070rik";
$dbPass = "********************";
$dbName = "portals";
$dbh = new PDO("mysql:host=$dbHost;dbname=$dbName", $dbUser, $dbPass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}
这是我试图访问的页面:
的https://***********.io/api/v2/ll/search/11
所有文件夹路径都很好,数据库连接正常。
希望有人有解决方案。
编辑添加.htaccess文件
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ %{ENV:BASE}index.php [QSA,L]
答案 0 :(得分:1)
您正在混合Slim 2和Slim 3代码。看来你正在使用Slim 3。
$app = new \Slim\App($c);
但是,您使用Slim 2语法定义路径。
app->get('/ll/search/:id', 'll_search');
使用Slim 3时,named placeholders的定义应如下所示。
app->get('/ll/search/{id}', 'll_search');
答案 1 :(得分:0)
我找到了解决方案,
我需要添加较旧版本的slim。
还是谢谢大家