我正在使用slim micro framework
开发一个php应用程序那是我的index.php文件:
FileTransfer
我有一个带有ajax跨域请求的index.html文件,如下所示:
<?php
require 'Slim/Slim.php';
include 'db.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->get("/", function () {
echo "<h1>HELLO USER</h1>";
});
//Registration view
$app->post("/reg", function (){
$request = $this->app->request();
$username = $request->post('username');
$password = $request->post('password');
$name = $request->post('name');
$email = $request->post('email');
try {
$sql = "INSERT INTO users (username, hash, name, email) VALUES (:username, :password, :name, :email)";
$s = $this->dbh->prepare($sql);
$s->bindParam("username", $username);
$s->bindParam("hash", $password);
$s->bindParam("name", $name);
$s->bindParam("email", $email);
$s->execute();
} catch(\PDOException $e) {
echo 'Exception: ' . $e->getMessage();
}
}); // Login Function End
$app->get('/updates', function () {
//Display users
});
// run the Slim app
$app->run();
?>
问题是,当我尝试在index.html文件中提交表单时,我总是得到:
致命错误:在第19行的C:\ wamp \ www \ slim \ index.php中不在对象上下文中时使用$ this
答案 0 :(得分:1)
$request = $this->app->request();
这很可能是#19行,它不在实例方法中,甚至不在类定义中。因此,没有实例引用,因此没有$ this
你期望这是什么?显然,您需要app
和dbh
。什么提供这些属性/实例?
app
可以是$app = new \Slim\Slim();
。但dbh
应该是什么? (数据库句柄,好的,但提供此数据库连接句柄的是什么?)
答案 1 :(得分:1)
基本上问题是@VolkerK提到的。
如果您希望闭包方法了解在方法范围之外定义的变量,则需要使用use
关键字。
$app->post("/reg", function () use ($app) {
$request = $app->request();
}
答案 2 :(得分:0)
<强>解决方案:强> 完整的工作index.php现在看起来像:
<?php
require 'Slim/Slim.php';
include 'db.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();
$app->contentType('application/json');
$app->get('/', 'home');
$app->post('/adduser', 'addUser');
$app->get('/users', 'getUsers');
// Home view
function home() {echo "Welcome to the platform !";}
// Add users
function addUser() {
global $app;
$req = $app->request();
$sql = "INSERT INTO users (username, password, fullname, email) VALUES (:username, :password, :fullname, :email)";
try {
$db = getDB();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $_POST['username']);
$password = md5($_POST['password']);
$stmt->bindParam("password", $password);
$stmt->bindParam("fullname", $_POST['fullname']);
$stmt->bindParam("email", $_POST['email']);
$stmt->execute();
$db = null;
} catch(PDOException $e) {
echo "Connection Error";
}
}
// Get Users
function getUsers() {
$sql = "SELECT username,fullname,email FROM users ORDER BY id";
try {
$db = getDB();
$stmt = $db->query($sql);
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
$db = null;
echo '{"users": ' . json_encode($users) . '}';
} catch(PDOException $e) {
//error_log($e->getMessage(), 3, '/var/tmp/php.log');
echo '{"error":{"text":'. $e->getMessage() .'}}';
}
}
// run the Slim app
$app->run();
?>