我用CodeIgniter做得很好。我可以在MySQL数据库上做SELECT语句,没有任何问题。但是,现在我试图做一个INSERT语句。
请注意,我还没有尝试使用UPDATE语句。
看完文档后,我很困惑。
这是我的:
contacts.php:
function add() {
//echo "<pre>";print_r($_POST);
$this->load->model('Contacts_model');
$this->Contacts_model->insertContact($_POST);
}
contacts_model.php:
function insertContact($_POST) {
//echo "<pre>";print_r($_POST);
$title = $_POST['title']; // I can echo this here. It works
$f_name = $_POST['f_name']; // I can echo this here. It works
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES (" .
$this->db->escape($title) .
"," .
$this->db->escape($f_name) .
")";
$this->$db->query($sql);
}
我读过有关活动记录的内容,但如果这就是我搞砸的原因,那么我仍然没有意识到我做错了什么。所有的例子都和我的一模一样。
帮助吗?
编辑
$sql = "INSERT INTO contacts (title,f_name) VALUES ('$this->db->escape($title)','$this->db->escape($f_name)'";
$this->$db->query($sql);
我也试过这样。还有很多其他的变体。这似乎不是我的语法…我认为。
你的查询很好,查询没有被执行的唯一原因是你正在使用这个:
$this->$db->query($sql);
没有像$db这样的东西,只要使用这个:
$this->db->query($sql);
我敢肯定这是问题,但如果不是,那么请张贴错误是什么给。谢谢。
您错过了引号字符:
$title = $this->db->escape($title);
$fname = $this->db->escape($f_name)
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES ('{$title}', '{$fname}')";
$this->db->query($sql);
顺便说一句,$_POST
变量是怎么回事?它是SuperGlobal变量之一。你不需要传递它的参数。你可以在脚本的任何地方安全地调用它。
另一个注意事项,由于您使用CodeIgniter,您最好检查Input
类库并使用它来满足所有输入需求。
Why send $_POST? Use $this->input->post("param_name") and in your instance "$this->load->model('Contacts_model');" in my practice i use "$this->load->model('Contacts_model','instance',[true or false]);" the last parameter is optional (to connect with the DB if you don't use autoload option).
Use this:
function insertContact() {
$title = $this->input->post("title");
$f_name = $this->input->post("f_name");
$sql = "INSERT INTO contacts (title,f_name) " .
"VALUES ('" . $this->db->escape($title) . "','".$this->db->escape($f_name) ."')";
$this->$db->query($sql);
}
DON'T USE $_POST! (And use the Active Record read the user guide)