I want to store data into database.
我想将数据存储到数据库中。
I tried this:
我试过这个:
In the View I created this form:
在视图中我创建了这个表单:
<form id="addControl" action="<?php echo URL ?>controles/addControl" method="POST">
<input type="text" name="text1">
<input type="text" name="text2">
<input type="text" name="text3">
<input type="submit" name="Add">
</form>
Then I created a Model
然后我创建了一个模型
controles_model.php
public function addControl(){
$text1 = $_POST['text1'];
$text2 = $_POST['text2'];
$text3 = $_POST['text3'];
$stmt = $this->db->prepare("INSERT INTO `controles` (field1, field2, field3 ) VALUES(?,?,?)");
$stmt->execute(array($text1,$text2,$text3));
if($stmt == true){
return "good";
}else{
return "wrong";
}
}
Then I created a Controller:
然后我创建了一个Controller:
controles.php
class Controles extends Controller {
function __construct(){
parent::__construct();
}
public function index(){
$this->view->render('controles/index');
}
function addControl(){
$this->model->addControl();
}
}
and finally, for the JS file I created this:
最后,对于我创建的JS文件:
$("#addControl").on('submit', function(e){
e.preventDefault();
var url = $(this).attr('action');
var data = $(this).serialize();
$.post(url, data, function(response) {
if(response == "good"){
$("#insertedSuccessfully").show();
}else if(response == "wrong"){
$("#notInserted").show();
}
});
});
All this doesn't work. How can I fix it?
这一切都行不通。我该如何解决?
NB: the database connection is OK, it work fine sine I can retreive data from database.
注意:数据库连接正常,它工作正常,我可以从数据库中检索数据。
2 个解决方案
#1
You have attached the event listener to the id addControl
but your form is having the id addData
. Therefore the var url might be undefined
in your javascript code.
您已将事件侦听器附加到id addControl,但您的表单具有id addData。因此,您的javascript代码中可能未定义var url。
and in your php file use $_POST
instead of $POST
.
并在您的PHP文件中使用$ _POST而不是$ POST。
Also I would recommend to check your console for any javascript errors
此外,我建议检查您的控制台是否有任何javascript错误
#2
$POST is not the array given by PHP, but is like more $_POST. So, in your model, you have no data to insert.
$ POST不是PHP给出的数组,但更像$ _POST。因此,在您的模型中,您没有要插入的数据。
#1
You have attached the event listener to the id addControl
but your form is having the id addData
. Therefore the var url might be undefined
in your javascript code.
您已将事件侦听器附加到id addControl,但您的表单具有id addData。因此,您的javascript代码中可能未定义var url。
and in your php file use $_POST
instead of $POST
.
并在您的PHP文件中使用$ _POST而不是$ POST。
Also I would recommend to check your console for any javascript errors
此外,我建议检查您的控制台是否有任何javascript错误
#2
$POST is not the array given by PHP, but is like more $_POST. So, in your model, you have no data to insert.
$ POST不是PHP给出的数组,但更像$ _POST。因此,在您的模型中,您没有要插入的数据。