hello mysql table is as below.
1.) edit-reference?id=58
When I enter the page, there is an error in my select operation, reference_categories all selected.
2.) Another issue is when I want to post the form
In the table "ref_sel_categories"
reference_id: 58 has reference_category_id: 92 in both columns.
table name 'reference'
id:58
referencetitle :helloword 1
id:59
referencetitle :helloword 2
table name 'reference_categories'
category_id: 92
category_name: word category 1
category_id: 93
category_name: word category 2
category_id: 94
category_name: word category 3
category_id: 95
category_name: word category 4
category_id: 96
category_name: word category 5
table 'ref_sel_categories'
id:1
reference_id:58
reference_category_id:92
id:2
reference_id:58
reference_category_id:93
id:3
reference_id:59
reference_category_id:94
id:4
reference_id:59
reference_category_id:94
id:5
reference_id:59
reference_category_id:94
$id = get('id');
$row = $db->from('reference')
->where('reference_id', $id)
->first();
$categories = $db->from('reference_categories')
->orderby('category_name', 'ASC')
->all();
$selectcategory = $db->from('ref_sel_categories')
->where('reference_id', $id)
->first();
if (post('submit')) {
$PostCategories = post('reference_categories');
if (!isset($error)) {
foreach ($_POST[$PostCategories as $selectedOption)
{
$update = $db->update('ref_sel_categories')
->where('reference_id', $id)
->set([
'reference_category_id' => $selectedOption,
]);
}
}
}
require 'edit-reference';
<form action="" method="post" enctype="multipart/form-data">
<select class="form-control" name="reference_categories[]" multiple data-max-options="4">
<?php foreach ($categories as $category): ?>
<option <?= ($_POST['reference_categories'] ? $_POST['reference_categories'] : $selectcategory['reference_category_id']) ? ' selected' : null ?>
value="<?= $category['category_id'] ?>"><?= $category['category_name'] ?></option>
<?php endforeach; ?>
</select>
<div class="card-footer ml-auto mr-auto">
<input type="hidden" name="submit" value="1">
<button type="submit" class="btn btn-warning">UPDATE</button>
</div>
</form>
<?php print_r($selectcategory['reference_category_id']) ?>
Database
I solved the problem. maybe it will help others.
$id = get('id');
$row = $db->from('reference')
->where('reference_id', $id)
->first();
$categories = $db->from('reference_categories')
->orderby('category_name', 'ASC')
->all();
$selectcategory = $db->from('ref_sel_categories')
->join('reference_categories', '%s.category_id = %s.reference_category_id')
->where('reference_id', $id)
->all();
$CatSelId = [];
foreach ($selectcategory as $SelCat) {
$CatSelId[] = trim($SelCat['reference_category_id']);
}
if (!isset($error)) {
$update = $db->update('reference')
->where('reference_id', $id)
->set($data);
if ($update) {
$postID = $id;
// Check and Add Any Changes in Category
$PostCategories = array_map('trim', $PostCategories);
$PostCategories = array_filter($PostCategories);
if (count($PostCategories) > 0) {
foreach ($PostCategories as $SelCat) {
// Kayıtlı Kategori var mı kontrol et
$row = $db->from('ref_sel_categories')
->where('reference_id', $id)
->where('reference_category_id', $SelCat)
->first();
if (!$row) {
$tagInsert = $db->insert('ref_sel_categories')
->set([
'reference_id' => $postID,
'reference_category_id' => $SelCat
]);
$ReferenceID = $db->lastId();
}
}
}
// Check Removed Selections! and delete
$diffs = array_diff($CatSelId, $PostCategories);
if (count($diffs) > 0) {
foreach ($diffs as $diff) {
foreach ($selectcategory as $allCategory) {
if (trim($allCategory['reference_category_id']) == $diff) {
$db->delete('ref_sel_categories')
->where('id', $allCategory['id'])
->where('reference_id', $id)
->done();
}
}
}
}
} else {
$error = 'Error';
}
}
<form action="" method="post" enctype="multipart/form-data">
<select class="form-control" name="reference_categories[]" multiple data-max-options="4">
<?php foreach ($categories as $category): ?>
<option <?= (post('reference_categories') ? post('reference_categories') : $CatSelId)
&& in_array($category['category_id'], (post('reference_categories') ? post('reference_categories') : $CatSelId)) ? 'selected' : null ?>
value="<?= $category['category_id'] ?>"><?= $category['category_name'] ?></option>
<?php endforeach; ?>
</select>
<div class="card-footer ml-auto mr-auto">
<input type="hidden" name="submit" value="1">
<button type="submit" class="btn btn-warning">UPDATE</button>
</div>
</form>
Related
How to get the checkbox data?
This is my view
<form method="post" action="<?= current_url();?>" >
<?php foreach($checklist as $item) : ?>
<ul>
<li>
<input type="hidden" name="name[]" value="<?= $item->name; ?>">
<div>
<label><?= $item->name; ?><label>
<input type="hidden" value="0" name="status=[]>
<input type="checkbox" value="1" name="status[]">
</div>
</li>
</ul>
<button type="submit">Submit</button>
</form>
this is my controller
public function checklist() {
if($this->request->getMethod() === 'post') {
$name = $this->request->getPost('nama');
$status = $this->request->getPost('status');
foreach($name as $key => $value) {
$checklist[] = [
'name' => $name[$key],
'status' => $status[$key]
];
}
$this->model->insertBatch($checklist);
return view('data',$data);
}
how to get the status if checked it get double array?
I assume this is a multi-item list with an item key. I assume $item['id'] is a unique key.
View
<?php
$checklist = [['id'=>1,'name'=>'Test name 1','status'=>1],
['id'=>2,'name'=>'Test name 2','status'=>0],
['id'=>3,'name'=>'Test name 3','status'=>1],
['id'=>4,'name'=>'Test name 4','status'=>0],
['id'=>5,'name'=>'Test name 5','status'=>0]];
?>
<pre>
<?=print_r($checklist)?>
</pre>
<form method="post" action="<?= current_url()?>" >
<ul>
<?php foreach($checklist as $item) : ?>
<li>
<input type="hidden" name="name[<?=$item['id']?>]" value="<?=$item['name']?>">
<div>
<label><?=$item['name']?><label>
<input type="checkbox" value="1" name="status[<?=$item['id']?>]"<?=$item['status']?' checked':''?>>
</div>
</li>
<?php endforeach;?>
</ul>
<button type="submit">Submit</button>
</form>
getPost
<pre>
<?php
if(isset($getPost))
print_r($getPost);
?>
</pre>
return
<pre>
<?php
if(isset($return))
print_r($return);
?>
</pre>
Controller
public function index()
{
$checklist = [];
if($this->request->getPost()) {
$getPost = $this->request->getPost();
$status = $this->request->getPost('status');
foreach($getPost['name'] as $key => $value) {
$checklist['return'][] = [
'name' => $value,
'status' => isset($status[$key])?1:0];
}
$checklist['getPost'] = $this->request->getPost();
// $this->Model->insertBatch($checklist);
}
return view('test',$checklist);
}
The final result image
Searchbar is working in codeigniter website but it does not load suggestion products. As I want if someone write 'dell' in searchbay he should get dell laptops suggestions below. and one another thing 'enter' button does not work for search one have to click the search icon to search the product.code is below
Controller
function text_search(){
if ($this->crud_model->get_settings_value('general_settings','vendor_system') !== 'ok') {
$search = $this->input->post('query');
$category = $this->input->post('category');
redirect(base_url() . 'index.php/home/category/'.$category.'/0-0/0/0/'.$search, 'refresh');
}else{
$type = $this->input->post('type');
$search = $this->input->post('query');
$category = $this->input->post('category');
if($type == 'vendor'){
redirect(base_url() . 'index.php/home/store_locator/'.$search, 'refresh');
} else if($type == 'product'){
redirect(base_url() . 'index.php/home/category/'.$category.'/0-0/0/0/'.$search, 'refresh');
}
}
}
Model
function get_type_name_by_id($type, $type_id = '', $field = 'name')
{
if ($type_id != '') {
$l = $this->db->get_where($type, array(
$type . '_id' => $type_id
));
$n = $l->num_rows();
if ($n > 0) {
return $l->row()->$field;
}
}
}
function get_settings_value($type, $type_name = '', $field = 'value')
{
if ($type_name != '') {
return $this->db->get_where($type, array('type' => $type_name))->row()->$field;
}
}
View
<div class="header-search">
<?php
echo form_open(base_url() . 'index.php/home/text_search/', array(
'method' => 'post'
));
?>
<input class="form-control" type="text" name="query" placeholder="<?php echo translate('what_are_you_looking_for');?>?"/>
<select
class="selectpicker header-search-select cat_select hidden-xs" data-live-search="true" name="category"
data-toggle="tooltip" title="<?php echo translate('select');?>">
<option value="0"><?php echo translate('all_categories');?></option>
<?php
$categories = $this->db->get('category')->result_array();
foreach ($categories as $row1) {
if($this->crud_model->if_publishable_category($row1['category_id'])){
?>
<option value="<?php echo $row1['category_id']; ?>"><?php echo $row1['category_name']; ?></option>
<?php
}
}
?>
</select>
<?php
if ($this->crud_model->get_type_name_by_id('general_settings','58','value') == 'ok') {
?>
<select
class="selectpicker header-search-select" data-live-search="true" name="type" onchange="header_search_set(this.value);"
data-toggle="tooltip" title="<?php echo translate('select');?>">
<option value="product"><?php echo translate('product');?></option>
<option value="vendor"><?php echo translate('vendor');?></option>
</select>
<?php
}
?>
<button class="shrc_btn"><i class="fa fa-search"></i></button>
</form>
</div>
<!-- /Header search -->
I have table ingredient w/c consist of(ingredient_id,name),category w/c consist of(category_id,name) and category_ingredients w/c consist of(ingredient_id,category_id). I created a form for adding many ingredients by category and It check if 1 or more ingredients already exists in that category then I will only have to get the id's of the ingredient and then the other ingredients that don't exist will be inserted in my DB. Please help me i really need your help :(
VIEW:
<?php echo form_open('dashboard/uploadIngredients', 'class="form-horizontal" enctype="multipart/form-data"'); ?>
<div class="form-group">
<div class="col-sm-10">
<select required class="form-control" name="ingredient_category">
<option value="" selected disabled>Select Ingredient Category</option>
<option value="All">All</option>
<?php foreach($this->products_model->getCategory() as $row): ?>
<option value="<?php echo $row->category_id ?>"><?php echo $row->category_name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="ingredients" rows="5" placeholder="Ingredients (EX. onion, oil, pasta)" required></textarea>
</div>
</div>
<div class='form-group'>
<div class="col-sm-10">
<button class="btn btn-lg btn-positive" type="submit"><i class="glyphicon glyphicon-ok"></i> Save Ingredient</button>
</div>
</div>
<?php echo form_close(); ?>
CONTROLLER:
public function uploadIngredients(){
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
if (!$this->products_model->getIngredientByName($value)) {
$saveData[] = array(
'ingredient_id' => null,
'name' => trim($value)
);
}
}
$ingredient_id = $this->products_model->saveIngredients($saveData);
foreach (explode(',', $this->input->post('ingredient_category')) as $key => $value)
{
foreach ( $ingredient_id as $key => $str ){
$joinData[] = array(
'ingredient_id' => $str,
'category_id' => intval($value)
);
}
$this->products_model->saveCategoryIngredients($joinData);
redirect('dashboard/add_ingredients');
}
MODEL:
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('ingredient_id', $value->ingredient_id);
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
return $insert_id;
}
public function getIngredientByName($name) {
$this->db->select('ingredient_id');
$this->db->limit(1);
$this->db->where('category_id', $category_id);
$ingredientQuery = $this->db->get('category_ingredient');
$ingredient_id = $ingredientQuery->row()->ingredient_id;
$this->db->select('name');
$this->db->where('ingredient_id', $ingredient_id);
$query = $this->db->get('ingredient');
foreach($query->result() as $row)
{
return $row->name;
}
}
I have table ingredient w/c consist of(ingredient_id,name),category w/c consist of(category_id,name) and category_ingredients w/c consist of(ingredient_id,category_id). I create a form for adding many ingredients by category and i want to check if 1 or more ingredients already exist then i will only have to get the id's of the ingredient and then the other ingredients that don't exist will be inserted in my db. can u guys help me pls?
Here's my code:
VIEW:
<?php echo form_open('dashboard/uploadIngredients', 'class="form-horizontal" enctype="multipart/form-data"'); ?>
<div class="form-group">
<div class="col-sm-10">
<select required class="form-control" name="ingredient_category">
<option value="" selected disabled>Select Ingredient Category</option>
<option value="All">All</option>
<?php foreach($this->products_model->getCategory() as $row): ?>
<option value="<?php echo $row->category_id ?>"><?php echo $row->category_name; ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="form-group">
<div class="col-sm-10">
<textarea class="form-control" name="ingredients" rows="5" placeholder="Ingredients (EX. onion, oil, pasta)" required></textarea>
</div>
</div>
<div class='form-group'>
<div class="col-sm-10">
<button class="btn btn-lg btn-positive" type="submit"><i class="glyphicon glyphicon-ok"></i> Save Ingredient</button>
</div>
</div>
<?php echo form_close(); ?>
CONTROLLER:
public function uploadIngredients()
{
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
$saveData[] = array('ingredient_id' => null,
'name' => trim($value)
);
}
$ingredient_id = $this->products_model->saveIngredients($saveData);
foreach (explode(',', $this->input->post('ingredient_category')) as $key => $value)
{
foreach ( $ingredient_id as $key => $str ){
$joinData[] = array(
'ingredient_id' => $str,
'category_id' => intval($value)
);
}
//var_dump($joinData); die();
$this->products_model->saveCategoryIngredients($joinData);
redirect('dashboard/add_ingredients');
}
}
MODEL:
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('ingredient_id', $value->ingredient_id);
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
return $insert_id;
}
public function saveCategoryIngredients($data)
{
foreach($data as $row => $value)
{
$this->db->insert('category_ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
return $insert_id;}
}
You just have to add a function to your model, like this :
<?php
public function getIngredientByName($name) {
return $this->db
->from('ingredient I')
->where('I.name', $name)
->get()->row(); //Will return the row of ingredient if ingredient exists, else null
}
And in your controller :
<?php
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
if (!$this->products_model->getIngredientByName($value)) {
$saveData[] = array(
'ingredient_id' => null,
'name' => trim($value)
);
}
}
Thanks Gwendal for answering this question i am modifying this answer a bit to prevent duplicate inserts e.g.:- if user inserts SuGar CaNe but we have in our database Sugar Cane then the with answer's code we will have 2 sugar cane to avoid these type of inserts we can use this code for model
<?php
public function getIngredientByName($name) {
return $this->db
->from('ingredient I')
-> where("( REPLACE( LOWER(I.name), ' ', '') LIKE '".strtolower(preg_replace('/\s+/', '', $name)) ."%')")
->get()->row(); //Will return the row of ingredient if ingredient exists, else null
}
for controller same as
<?php
foreach(explode(',', $this->input->post('ingredients')) as $key => $value)
{
if (!$this->products_model->getIngredientByName($value)) {
$saveData[] = array(
'ingredient_id' => null,
'name' => trim($value)
);
}
}
I'm building my own book library management system using Codeigniter. I get stuck when I want to buil search engine using filtered keyword. I have four tables (books, publisher, category, format) and I use join to retrieve data. But the results were not what I excepted. Below I show my codes:
// TABLE STRUCTURE
Books |book_id, publisher_id, cat_id, format_id, title, author, ... etc|
Publisher |publisher_id, publisher, address|
Category |cat_id, category, description|
Format |format_id, format|
// MODEL
public function findBooks ( $keyword, $publisher, $category, $format, $offset, $limit )
{
$this->db->select('*');
$this->db->join('publisher as p', 'b.publisher_id=p.publisher_id', 'left');
$this->db->join('category as c', 'b.cat_id=c.cat_id', 'left');
$this->db->join('format as f', 'b.format_id=f.format_id', 'left');
if(!empty($keyword)) {
$this->db->like('b.title', $keyword);
$this->db->like('p.publisher', $publisher);
$this->db->or_like('c.category', $category);
$this->db->or_like('f.format', $format);
}
$this->db->order_by('book_id', 'ASC');
$getData = $this->db->get('books as b', $offset, $limit);
if($getData->num_rows() > 0)
{
return $getData->result();
} else {
return NULL;
}
}
public function getPublishers()
{
$query = $this->db->query("SELECT * FROM publisher ORDER BY publisher_id ASC");
return $query;
}
public function getCategories()
{
$query = $this->db->query("SELECT * FROM category ORDER BY cat_id ASC");
return $query;
}
public function getFormat()
{
$query = $this->db->query("SELECT * FROM format ORDER BY format_id ASC");
return $query;
}
// BOOKS CONTROLLER
public function find($keyword='', $offset = '', $limit = 3;)
{
if($this->uri->segment(3) === FALSE){
$offset = 0;
}else{
$offset = ($this->uri->segment(3)-1) * $limit;
}
$keyword = mysql_real_escape_string($this->input->post('term'));
$publisher = $this->input->post('publisher_id');
$category = $this->input->post('cat_id');
$format = $this->input->post('format_id');
$check = $this->adminModel->findBooks( $keyword, $publisher, $category, $format, $offset, $limit );
if($check)
{
$data['message'] = "";
$data['res'] = $check;
$this->load->view('search_result', $data);
} else {
$data['message'] = "<div class='alert alert-warning'>No result. Please try with another keyword.</div>";
$this->load->view('search_result', $data);
}
}
// FORM VIEW
<div>
<h4>Find Books</h4>
<form action="<?php base_url(); ?>books/find" method="POST" class="form-horizontal" role="form">
<div class="input-group input-group col-md-12">
<label for="term" class="sr-only"></label>
<input type="text" class="form-control" name="term" placeholder="Enter Keyword">
</div>
<div class="input-group col-md-12">
<label for="publisher">By Publisher</label>
<select name="publisher" id="publisher" class="form-control">
<option value="0">All</option>
<?php foreach ($pub->result() as $p) { ?>
<option value="<?php echo $p->publisher_id; ?>"<?php echo set_select('publisher_id', $p->publisher_id, (!empty($data) && $data == $p->publisher_id ? TRUE : FALSE )); ?>><?php echo ucwords($p->publisher); ?></option>
<?php ; } ?>
</select>
</div>
<div class="input-group col-md-12">
<label for="category">By Category</label>
<select name="category" id="category" class="form-control">
<option value="0">All</option>
<?php foreach($cats->result() as $cat){ ?>
<option value="<?php echo $cat->cat_id; ?>"<?php echo set_select('cat_id', $cat->cat_id, (!empty($data) && $data == $cat->cat_id ? TRUE : FALSE )); ?>><?php echo ucwords($cat->category); ?></option>
<?php } ?>
</select>
</div>
<div class="input-group col-md-12">
<label for="format">By Format</label>
<select name="format" id="format" class="form-control">
<option value="0">All</option>
<?php foreach ($format->result() as $frm) { ?>
<option value="<?php echo $frm->format_id; ?>"><?php echo set_select('format', $frm->format_id, (!empty($data) && $data == $frm->format_id ? TRUE : FALSE )); ?><?php echo ucwords($frm->format); ?></option>
<?php ; } ?>
</select>
</div>
<div class="input-group col-md-12">
<button type="submit" class="btn btn-success">FIND</button>
</div>
</form>
</div>
Here what I except is, for instance, I search term "Adam" and it might be a name of person, publisher, or part of title. So, if I search the keyword "Adam" and filtered ONLY by publisher, it will show result such as Adam Publishing rather than "History of Adam and Eve" (as book title).
Another question, am I getting wrong in my code? If so, give me direction what it should be.
Best regards