CODEIGNITER: check if ingredient exist - php

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)
);
}
}

Related

Codeigniter - select dropdown wont updated

i have a form which included an select dropdown which is id_constructor, the problem is the all remaining data is updated into the database except the id_constructor, my table looks like this :
teams
id_team
name
id_constructor
created_at
modified_at
And here is my code :
Controller :
$this->load->database();
$this->load->helper('form');
$this->load->library(array('form_validation'));
$this->load->model('back-end/m_masterteam','teams');
$this->load->model('back-end/m_masterconstructors','constructors');
public function edit($id_team)
{
$data['teams_data'] = $this->teams->getTeam($id_team);
$data['constructors_data'] = $this->constructors->getAllConstructor();
$this->load->view('back-end/template/header');
$this->load->view('back-end/edit-team', $data);
$this->load->view('back-end/template/footer');
}
public function updateTeam()
{
$id_team = $this->input->post('id_team');
$name = $this->input->post('name');
$id_constructor = $this->input->post('id_constructor');
$modified_at = $this->input->post('modified_at');
$data = array(
'id_team' => $this->input->post('id_team'),
'name' => $this->input->post('name'),
'id_constructor' => $this->input->post('id_constructor'),
'modified_at' => date('Y-m-d H:i:s')
);
// print_r($data);exit();
$this->teams->update($data, $id_team);
echo json_encode(array("status" => TRUE));
redirect('admin-page/MasterTeam/');
}
Model :
var $table = 'teams';
var $column = array('name','id_constructor','created_at','modified_at');
var $order = array('teams.name' => 'desc');
function update($data, $id_team)
{
$this->db->where('id_team', $id_team);
$this->db->update('teams', $data);
}
And here is the view for the select option :
<form action="<?php echo base_url('admin-page/MasterTeam/updateTeam') ?>" method="post">
<div class="form-group row">
<label for="inputPassword" class="col-sm-2 col-form-label">Constructor</label>
<div class="col-sm-10">
<select class="form-control" name="id_constructor">
<?php foreach($constructors_data as $row)
{?>
<option value="<?php echo $teams_data->id_constructor; ?>"<?php if($row->id_constructor==$teams_data->id_constructor) echo 'selected="selected"';?>><?php echo $row->name; ?></option>
<?php
}
?>
</select>
</div>
</div>
And here is the result for print_r() :
Array ( [id_team] => 16 [name] => test21 [id_constructor] => 3
[modified_at] => 2022-02-28 13:42:11 )
all data except the id_constructor is updated in the database, anyone know the solution? any help is really appreciated. thank you!.

Php Mysql multiple Selected Option

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>

Codeigniter Update method Issue when adding array values into DB

Trying to update college profile which contains all the college info in the database, Some records are manually filled in by data entry, some records have to be updated by the college admin or super admin.
The issue is when I insert an array (Facilities[ ]) into the Db it inserts without any errors, but when i update the same it gives me an error.
The Insertion was done through another controller with insert statement
$company_id = $this->companies_model->add_company($company_array);
which works flawlessly, But update function gives me this error
Error Number: 1054
Unknown column 'Array' in 'field list'
UPDATE pp_companies SET facilities = Array, company_description = 'Established in the year....', company_join = 'Why Join us', WHERE ID = '201'
Filename: C:\xampp\htdocs\jobportal\jp_sys\database\DB_driver.php
Line Number: 287
Facilities = 'Array'? any idea how this shows?
Array ( [0] => Engineering [1] => Management )
sends the value when i check through
print_r($this->input->post('facilities'));
But it doesnt get updated in the table
View
<div class="input-group <?php echo (form_error('company_description'))?'has-error':'';?>">
<label class="input-group-addon">College<br> Description <span>*</span></label>
<textarea class="form-control" name="company_description" id="company_description" rows="8" cols="30" ><?php echo $company_description; ?></textarea>
<?php echo form_error('company_description'); ?> </div>
<div class="input-group <?php echo (form_error('company_join'))?'has-error':'';?>">
<label class="input-group-addon">Why join <br> our College? <span>*</span></label>
<textarea class="form-control" name="company_join" id="company_join" rows="8" cols="30" ><?php echo $company_join; ?></textarea>
<?php echo form_error('company_join'); ?> </div>
<?php echo $facilities ?>
<div class="input-group boxwraper <?php echo (form_error('facilities'))?'has-error':'';?>">
<label class="input-group-addon">Facilities Offered <span></span></label>
<select name="facilities[]" class="js-example-tags" multiple="multiple">
<option value="Library" >Library</option>
<option value="Gym" >Gym</option>
<option value="Canteen" >Canteen</option>
.
.
</select>
</div>
<script type="text/javascript">
$(".js-example-tags").select2({
tags: true
})
</script>
Model
public function add_company($data){
$return = $this->db->insert('pp_companies', $data);
if ((bool) $return === TRUE) {
return $this->db->insert_id();
} else {
return $return;
}
}
public function update_company($id, $data){
$this->db->where('ID', $id);
$return=$this->db->update('pp_companies', $data);
return $return;
}
Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Edit_College extends CI_Controller {
public function index()
{
$row = $this->employers_model->get_employer_by_id($this->session->userdata('user_id'));
$data['row'] = $row;
$data['title'] = $row->company_name.' - Edit Profile';
$this->form_validation->set_rules('facilities[]', 'Facilities', 'trim|required|strip_all_tags');
$this->form_validation->set_rules('company_description', 'Company Description', 'trim|required|strip_all_tags|secure');
$this->form_validation->set_rules('company_join', 'Company Join', 'trim|required|strip_all_tags|secure');
$data['facilities'] = (set_value('facilities'))?set_value('facilities'):$row->facilities;
$data['company_description'] = (set_value('company_description'))?set_value('company_description'):$row->company_description;
$data['company_join'] = (set_value('company_join'))?set_value('company_join'):$row->company_join;
if ($this->form_validation->run() === FALSE) {
$this->load->view('employer/edit_company_profile_view',$data);
return;
}
//for facility addition into db
$arrcategory1 = $this->input->post('facilities');
foreach($arrcategory1 as $val1)
{
$categoryarr1 = $categoryarr1 . $val1. ",";
}
$categoryarr1 = substr(trim($categoryarr1), 0, -1); //rtrim($categoryarr,",")
$company_array = array(
'facilities'=> $arrcategory1,
'company_description' => $this->input->post('company_description'),
'company_join' => $this->input->post('company_join'),
$this->companies_model->update_company($row->company_ID, $company_array);
$this->session->set_flashdata('msg', '<div class="alert alert-success">×<strong>Success!</strong> Your company profile has been updated.</div>');
$this->session->set_userdata('slug',$company_slug);
redirect(base_url('employer/edit_college'));
}
}

CODEIGNITER: Check if exist

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;
}
}

prohibit adding existing value in a multidimensional array

I have a table ingredient w/c consist of(ingredient_id,name). I can perfectly add an ingredient. But i want to add a condition that prohibit on adding existing ingredient. I have the code for that condition but i think it's wrong because the condition didn't work and i can still add an existing ingredient. please help me
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->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);
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);
if($query->num_rows > 0) {
echo '<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>';
echo "Ingredient already taken";
echo '</strong></div>';
} else {
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
}
return $insert_id;
}
Change your model to
public function saveIngredients($ingredient_id)
{
foreach($ingredient_id as $row => $value) {
$query=$this->db->where('name', $value->name);
if($query->num_rows > 0) {
echo '<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>';
echo "Ingredient already taken";
echo '</strong></div>';
} else {
$this->db->insert('ingredient', $value);
$insert_id[] = $this->db->insert_id();
}
}
return $insert_id;
}
That should do it. Just changing the $query line.
If that doesn't work, do a var_dump on $value just above that line, so you can see if you need to adjust the value you're targeting.
Use below code.
CONTROLLER:
public function uploadIngredients()
{
foreach(explode(',', $this->input->post('ingredients')) as $key => $value) {
$result = this->products_model->saveIngredients(trim($value));
if($result['status'])
{
$ids[]=$result['id'];
}else{
echo '<div class="alert alert-error"><a class="close" data-dismiss="alert">×</a><strong>';
echo "Ingredient already taken";
echo '</strong></div>';
}
}
redirect('dashboard/add_ingredients');
} }
MODEL:
public function saveIngredients($data)
{
$query=$this->db->where('name', $data);
if($query->num_rows > 0) {
return ['status'=>FALSE];
} else {
$this->db->insert('ingredient', array('name'=>$data));
$insert_id = $this->db->insert_id();
return ['status'=>TRUE,'id'=>$insert_id];
}
}

Categories