我是 CI 新手,一直在阅读文档并遵循 form tutorial 。然而,我正在努力将我的表单写入我的数据库。实际上,数据正在写入,但我收到错误...
A PHP Error was encountered
Severity: Notice
Message: Use of undefined constant firstname - assumed 'firstname'
Filename: controllers/form.php
Line Number: 25
我在写姓氏的第二个字段中也遇到了错误。我认为我已经足够接近 MySQL 正在弄清楚我想要做什么,但我仍然错过了一些东西。
我的表单/ View ...
<html>
<head>
<title>Pledge Details</title>
</head>
<body>
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h5>First Name</h5>
<input type="text" name="firstname" value="<?php echo set_value('firstname'); ?>" size="50" />
<h5>Last Name</h5>
<input type="text" name="lastname" value="<?php echo set_value('lastname'); ?>" size="50" />
<h5>Email Address</h5>
<input type="text" name="email" value="<?php echo set_value('email'); ?>" size="50" />
<h5>Kms/Miles</h5>
<select name="myselect">
<option value="Kms" <?php echo set_select('myselect', 'Kms', TRUE); ?> >Kms</option>
<option value="Miles" <?php echo set_select('myselect', 'Miles'); ?> >Miles</option>
</select>
<h5>Pledge</h5>
<input type="text" name="pledge" value="<?php echo set_value('pledge'); ?>" size="50" />
<br><br>
<div><input type="submit" value="Submit" /></div>
</form>
<?php echo form_close() ?>
</body>
</html>
我的 Controller ...
<?php
class Form extends CI_Controller {
function index()
{
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('firstname', 'First Name', 'trim|required|max_length[12]|xss_clean');
$this->form_validation->set_rules('lastname', 'Last Name', 'trim|required|max_length[12]|xss_clean');
$this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
$this->form_validation->set_rules('pledge', 'Pledge', 'trim|required|max_length[12]|decimal|xss_clean');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('myform');
}
else
{
$this->load->database();
$sql = "INSERT INTO donations (firstname, lastname)
VALUES (".$this->db->escape($_POST[firstname]).", ".$this->db->escape($_POST[lastname]).")";
$this->db->query($sql);
echo $this->db->affected_rows();
$this->load->view('formsuccess');
}
}
}
?>
最佳答案
您的错误来自以下行
$sql = "INSERT INTO donations (firstname, lastname) VALUES (".$this->db->escape($_POST[firstname]).", ".$this->db->escape($_POST[lastname]).")";
您忘记将 $_POST
变量括在引号中。请注意 $_POST[firstname]
已变为 $_POST['firstname']
。应该是
$sql = "INSERT INTO donations (firstname, lastname) VALUES (".$this->db->escape($_POST['firstname']).", ".$this->db->escape($_POST['lastname']).")";
就像其他人所说的那样,您可以执行 $this->input->post('firstname');
关于php - 如何正确地将表单数据传递到CodeIgniter中的数据库函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22297260/