gpt4 book ai didi

php - 获取最后插入 id 并将数组或多个值保存到 mysql 数据库 codeigniter

转载 作者:行者123 更新时间:2023-11-29 18:04:29 26 4
gpt4 key购买 nike

我真的需要你的帮助,我已经为此工作了几周,我有一个动态字段,它是一个名为“size”的数组,并且有一个名为“category”的字段,对于每个类别都有一个或多个尺寸。现在我需要将数据保存到两个表中。类别和大小是相互关联的,这里:

(我的数据库表)

CREATE TABLE `category` (
`category_id` int(11) NOT NULL AUTO_INCREMENT,
`category_name` varchar(55) NOT NULL,
PRIMARY KEY (`category_id`)
)
CREATE TABLE `sizes` (
`size_id` int(11) NOT NULL AUTO_INCREMENT,
`size` varchar(45) NOT NULL,
`category_id` int(11) NOT NULL,
PRIMARY KEY (`size_id`),
KEY `cat_fk_idx` (`category_id`),
CONSTRAINT `cat_fk` FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`) ON DELETE NO ACTION ON UPDATE NO ACTION
)

这是我的观点(category.php)

<div class="col-sm-5">
<?php echo $this->session->flashdata('errorMessage');?>
<?php echo $this->session->flashdata('successMessage');?>
<?php echo form_open('category_con/add_category'); ?>
<?php echo form_fieldset('<h1 class="text-danger">Categories</h1>'); ?>
<div class="form-group">
<label for='Username'>Add New Category</label>
<input type="text" name="category_name" class="form-control" placeholder="Add new Category here">
</div>



<script src="assets/js/jquery.min.js"></script>

<div class="form-group">
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="size[]" placeholder="Add Size" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>

</div>
</form>
</div>
<div class="form-group">
<input type="submit" name="save_category" class="btn btn-success" value="Save Category">
</div>
</div>

<script>
$(document).ready(function(){
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="size[]" placeholder="Add Size" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});

});
</script>


<?php echo form_close(); ?>

我的 Controller (category_con.php)

public function add_category( ) {
$this->form_validation->set_rules('category_name', 'Category', 'required|alpha');


if ($this->form_validation->run() == FALSE) {
$this->session->set_flashdata('errorMessage', '<div class="alert alert-danger"> '.validation_errors() . '</div>');
redirect(base_url('categories'));
}else {

$this->load->model('categories_model');


$exec = $this->categories_model->categorysize();
if ($exec) {
$this->session->set_flashdata('successMessage', '<div class="alert alert-success"> Category Added Successfully</div>');
redirect(base_url('categories'));
}else {
$this->session->set_flashdata('errorMessage', '<div class="alert alert-danger">Opps... Something Went Wrong Please Try Again.</div>' );
redirect(base_url('categories'));

}

}
}

还有我的模型 (categories_model.php)

public function categorysize()
{
$this->load->database();
$category_name = $this->input->post('category_name');



$this->db->query("INSERT INTO category (category_name) VALUES (".$this->db->escape($category_name).")");

$last_row_id = $this->db->insert_id(); // Gets last row id ( category_id )
for($i = 0; $i < count ($_POST['size']); $i++){
$form_data[] = array(

'size' => $_POST['size'][$i] ,
'category_id' => "$last_row_id"

);


$this->db->insert_batch('sizes', $form_data);

}
}

单击“保存”按钮后,会将类别保存在类别表中,并将尺寸保存在尺寸表和category_id上,但第一个输入会重复。它显示错误消息“Opps...出问题了,请重试”,我将其放在 Controller 上,但如果删除错误消息,即使我重定向页面,我也会得到一个 blnk 页面。

希望你能帮助我。谢谢!!

最佳答案

我相信以下内容会有所帮助。首先,模型。它需要返回 Controller 可以使用的东西。

class Categories_model extends CI_Model
{

public function __construct()
{
parent::__construct();
$this->load->database(); //Or do this in autoload.php
}

public function categorysize()
{
$category_name = $this->input->post('category_name');

// using insert() like this will automatically escape $category_name
$this->db->insert("category", ['category_name' => $category_name]);

$last_row_id = $this->db->insert_id(); // Gets last row id ( category_id )

$form_data = []; //empty array, just in case

$sizes = $this->input->post('size'); //safer than using $_POST directly
foreach($sizes as $size)
{
$form_data[] = array('size' => $size, 'category_id' => "$last_row_id");
}

// insert_batch() returns number of rows inserted or FALSE on failure
// so the next line will return TRUE as long as insert_batch() doesn't return FALSE
return FALSE !== $this->db->insert_batch('sizes', $form_data);
}

}

在 Controller 中,您现在可以使用 if 语句从模型返回来进行测试

public function add_category()
{
$this->form_validation->set_rules('category_name', 'Category', 'required|alpha');

if($this->form_validation->run() === FALSE) //use the explicit comparison operator ===
{
$this->session->set_flashdata('errorMessage', '<div class="alert alert-danger"> '.validation_errors().'</div>');
redirect(base_url('categories'));
}
// You don't need an else block because the if block ends the script when it runs
// Script is ended by redirect() which does not return to this code

$this->load->model('categories_model');

if($this->categories_model->categorysize())
{
$this->session->set_flashdata('successMessage',
'<div class="alert alert-success"> Category Added Successfully</div>');
}
else
{
$this->session->set_flashdata('errorMessage',
'<div class="alert alert-danger">Opps... Something Went Wrong Please Try Again.</div>');
}
redirect(base_url('categories'));
}

以下内容不会影响输出,但会减少您必须执行的输入操作。每当您连续有多个 php 命令时,您不需要将每个命令都用 <?php ?> 括起来。标签。然后,在您的 View 中将所有线条像这样包围一次

<?php 
echo $this->session->flashdata('errorMessage');
echo $this->session->flashdata('successMessage');
echo form_open('category_con/add_category');
echo form_fieldset('<h1 class="text-danger">Categories</h1>');
?>

关于php - 获取最后插入 id 并将数组或多个值保存到 mysql 数据库 codeigniter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48011066/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com