I want to loop through the results of a query and then compare each results to an input field, if the value is repeated it must return false if not the result is true, I know that I could use unique index in database to avoid repeated values and then catch the error, but in this case repeated values are possible but they can´t both be "active" there a column called "status" with two values A or I (active and inactive) so "clabe" value can be repeated only when one is active and the other inactive.
Controller:
function agregar()
{
$this->load->helper('date');
date_default_timezone_set('America/Mexico_City');
$now = date('Y-m-d H:i:s');
$Interno = $this->input->post('intern');
$clabe = $this->input->post('clabe2') . $this->input->post('control2');
$cve_banco = $this->input->post('cve_banco');
$Banco = $this->input->post('Banco2');
$Observaciones = $this->input->post('Observaciones');
$data = array(
'Interno' => $Interno,
'clabe' => $clabe,
'cve_banco' => $cve_banco,
'Banco' => $Banco,
'Observaciones' => $Observaciones,
'Fecha_alta' => $now,
);
if($this->consultas_M->insert($data) == true){
//redirect('Inicio/busqueda', 'refresh');
} else{
echo "Hubo un problema al insertar";
}
}
Model:
function insert($data)
{
$clabe = $this->input->post('clabe2') . $this->input->post('control2');
$this->db->select('Clabe');
$this->db->where('Status =', 'A');
$query= $this->db ->get('cuentas');
return $query->row();
foreach ($query as $row) {
$i = $row;
if ($clabe = $i) {
return false;
} else {
$this-> db -> insert('cuentas', $data);
if ($this->db->affected_rows() > 0) {
return true;
}
}
}
}
Why would you want to have possible duplicated index ? If you want to have different rows with a common "index" for some reason you can create a column called index or something and add in your WHERE clause that index.
PS: in your model in the foreach loop's if condition use :
if ($clabe == $row){...
instead of
$i = $row
if ($clabe = $i){...
I solved myself the issue, i´m posting in in case it helps anybody, it was easier than I thought.
function insert($data, $clabe)
{
$Status = 'A';
$clabe = $this->input->post('clabe2') . $this->input->post('control2');
$this->db->select('Clabe');
$this->db->where('Status =', $Status);
$this->db->where('Clabe =', $clabe);
$q= $this->db ->get('cuentas');
if($q -> num_rows() > 0){
return false;
}else{
$this-> db -> insert('cuentas', $data);
return true;
}
And this is the controller:
if($this->consultas_M->insert($data, $clabe) == true){
redirect('Inicio/busqueda', 'refresh');
} else{
echo "There was a problem";
$this->load->view('errors/error');
}
The only thing I needed and wasn´t doing was to select the "clabe" I wanted and then compare it with the input where user writes this "clabe". And then just a simple if-else statement.
function insert($data)
{
$Status = 'A';
$clabe = $this->input->post('clabe2') . $this->input->post('control2');
$this->db->select('Clabe');
$this->db->where('Status', $Status);
$query= $this->db ->get('cuentas');
$flag=true;
foreach ($query as $row) {
$i = $row;
if ($clabe = $i){
$flag=false;
}
}
if($flag){
$this-> db -> insert('cuentas', $data);
if ($this->db->affected_rows() > 0) {
$flag= true;
}
}
return $flag;
}
Your code will add it on first else block ad return. Instead it should check all the rows first to decide.
Related
I have the following function in my model to filter officer records user wise. The function is working fine.
public function getOfficer()
{
$q = $this->db->order_by('last_name','ASC')->get_where('tbl_officer', array('status' => '1', 'usr' =>$this->session->userdata('id_user')));
if ($q->num_rows() > 0) {
return $q->result();
}
return false;
}
Further, I want to filter officer records only for the user = 4 in the session, by p_code->8,10 and 24
The If functions as follows :
if($usr == 4)
{
$this->datatables->where('tbl_officer.p_code', 8)->or_where('tbl_officer.p_code', 10)->or_where('tbl_officer.p_code', 24);
} else {
$this->datatables->where('tbl_officer.usr', $usr);
}
How can I include this If condition into my model function mentioned above ? What can be changed ? Can anyone help ?
PLease use where_in
$this->datatables->where('tbl_officer.p_code', 8)->or_where('tbl_officer.p_code', 10)->or_where('tbl_officer.p_code', 24);
to
$this->datatables->where_in('tbl_officer.p_code', [8,10,24]);
Just need to change the method of query writing
public function getOfficer()
{
$usr = $this->session->userdata('id_user');
$userArray = array(8,10,24);
$this->db->select('*');
$this->db->from('tbl_officer');
if($usr == 4){
$this->db->where_in('usr',$userArray );
}else{
$this->db->where('usr',$usr);
}
$q = $this->db->get();
if ($q->num_rows() > 0) {
return $q->result();
}
return false;
}
I'm using codigniter 3.1.2 and using simple if condition in php but really confused when I checked my condition is true getting result from else condition as well and if as well mean getting data in from both cases.
public function editexperience($UserID = 0, $ID = 0) {
if ($this->Access->HaveAccess('Edit')) {
$Row = $this->Experience->Row($ID);
if ($ID > 0 && $Row){
print_r($Row);
Def(array(
'Update'=>'users/submit/updateexperience/'
),'Actions');
$User = $this->Model->Row(intval($UserID), '', 'CTRY.Currency');
$ID = intval($ID);
$Data['Row'] = $Row;
Def($Row,'Row');
$Data['Title'] = 'Edit Experience';
$Data['Fields'] = $this->GetExperienceFields($User->Currency, true);
$this->Main->SetPage('Helper/Edit', $Data, true);
} else {
TempNote('There is problem while getting request data!', 'Error');
redirect(URI(_E('{Page.List}'), true), 'refresh');
die();
}
}
}
In code I mentioned if I have Row then load template of edit.
Suppose:
I have Row and its loading edit template and also showing the error of else condition really confuse what is happening.
My PHP version is 5.6.31
TempNote Function
function TempNote($Message, $Type) {
//Prepare Data
$Current = array('Message'=>$Message,'Type'=>$Type);
//Get current instance
$Ins = & get_instance();
$Old = $Ins->Main->Messages;
// If another is already set and that should not be current
if (!empty($Old)) {
foreach ($Old as $Key=>$Now) {
if ($Now === $Current){
unset($Old[$Key]);
}
}
}
$Ins->Main->Messages[] = $Current;
$Ins->session->set_flashdata('Message', $Ins->Main->Messages);
}
I am working with rest api using codeigniter,I want to fetch records + total records + per page records,but not worked for me
Here is my function in controller
<?php
public function search_shop()
{
$users['rec'] = $this->Model_users->find_shop($_POST);
if($users['rec']!="")
{
$responseJSON = array("Status" => true,"Result" => $users['rec']);
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
else
{
$responseJSON = array("Status" => false,"Message" => "There is no matching record");
header("content-type:application/json");
$response = json_encode($responseJSON);
echo $response;
}
}
And here is my "find_shop" function in model,How can i fetch all records with total number of records and per page records ?
public function find_shop()
{
$add_data['page_number'] = ($this->input->post('page_number') && !empty($this->input->post('page_number'))) ? $this->input->post('page_number') : NULL;
$add_data['search'] = ($this->input->post('search') && !empty($this->input->post('search'))) ? $this->input->post('search') : NULL;
$records="10";
$mins="10";
if($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
{
$starting_row="0";
$last_row="10";
}
else
{
$last_row="9";
$cd="1";
$lim="10";
$starting_row=$add_data['page_number']*$lim-$last_row-$cd;
$last_row=$add_data['page_number']*$records-$cd;
}
$this->db->select('*');
$this->db->from('shop s');
$this->db->like('shop_name',$add_data['search']);
$this->db->or_like('city',$add_data['search']);
$this->db->limit($last_row,$starting_row);
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$row = $query->result_array();
return $row;
return $query->num_rows;
}
else
{
return false;
}
}
?>
Try This, Hope it helps
in the Controller please test this after model related changes
$users = array();
$users = $this->Model_users->find_shop($_POST);
echo'<pre>';print_r($users);die;
in the Model, There is a mistake in the return, You cannot do two return at the same time
$query = $this->db->get();
if ( $query->num_rows() > 0 )
{
$data = array();
$data['row'] = $query->result_array();
$data['total_records'] = $this->db->count_all_results('shop');
$data['per_page_records'] = $query->num_rows();
return $data;
}else{
return array('row'=>array(),'total_records'=>'0','per_page_records'=>'0');
}
Change your if condition like this:
$records="10"; // This is records per page showing
if ($add_data['page_number']=="" || $add_data['page_number']=="0" || $add_data['page_number']=="1")
{
$starting_row="0";
} else {
$starting_row = ($add_data['page_number'] - 1) * $records;
}
You need to set limit and offset of query. For example: limit 0, 10: this will show first 10 records. Here 0 is starting point and 10 is the length of records which you want to show. 10 will always be same as you are showing 10 records. Limit 10, 10: it will show records from 10 to 19. hope it clears your doubt.
How to implode and insert values into the database in CodeIgniter?
I am creating multiple choice quiz script using CodeIgniter framework. I want to store user results like this:
id userid q_id answer_id time_taken
1 1 1,2,3,4,5 2,3,4,5,3 4,5,7,6,7
in my controller:
public function insert_result()
{
$this->load->model('quiz_models');
$user_id=$this->input->post('user_id');
$qq_id=$this->input->post('questionid');
$answer_id=$this->input->post('AnswerID');
$time_taken=$this->input->post('timetaken');
$question_no=$this->input->post('question_no');
$bd = "$question_no";
switch ($bd) {
case"1":
$data=array('user_id'=>$user_id,
'q_id'=>$qq_id,
'answer_id'=>$answer_id,
'time_taken'=>$time_taken);
$this->quiz_models->insert_result($data);
break;
case"2":
quiz_test();
break;
case"3":
quiz_test();
break;
case"4":
quiz_test();
break;
case"5":
quiz_test();
$this->session->unset_userdata('lastids');
break;
default:
echo "something is wrong";
}
}
public function quiz_test()
{
$this->load->model('quiz_models');
$quiz=$this->quiz_models->quiz_test();
foreach($quiz as $row){
$qid=$row->q_id;
$ans=$row->answer_id;
$time=$row->time_taken;
$a = array("$qq_id","$qid");
$b = array("$answer_id","$ans");
$c = array("$time_taken","$time");
$comma = implode(",",$a);
$comma1 = implode(",",$b);
$comma2 = implode(",",$c);
$data=array('q_id'=>$comma,
'answer_id'=>$comma1,
'time_taken'=>$comma2);
$this->quiz_model->update_result($data);
}
}
}
and Model:
function insert_result($data)
{
$this->dbb->insert('results',$data);
$sectio=$this->db->insert_id();
$this->session->set_userdata('lastids',$sectio);
}
function quiz_test()
{
$ses_id = $this->session->userdata('lastids');
$sql = "SELECT q_id, answer_id, time_taken FROM results WHERE id='$ses_id'";
$query = $this->dbb->query($sql);
$result = $query->result();
return $result;
}
function update_result($data){
$ses_id = $this->session->userdata('lastids');
$this->db->where('id',$ses_id);
$this->db->update('results',$data);
}
when i run it nothing happened,not showing any error where do i mistake?
pls help me what am i doing wrong
First of all - i think you've a major problem in your DB structure
Normalize your Data
You should prevent to store your information in the table like that.
It should be possible to normalize your data properly. If you dont know
how to do that the following link could be interesting:
Normalization in MYSQL
However a possible solution would be to structure your data:
In order to do that - create a save Method in your Model to split between update and insert - this model could look like
class Quiz_Models
{
private $arrPostData;
public function save($arrPostData = false)
{
$this->arrPostData = (!$arrPostData) ? $this->input->post() : $arrPostData;
$id = $this->session->userdata("lastids");
if ($id)
{
$query = $this->db
->select("*")
->from("results")
->where("id",$id)
->get();
if ($query->num_rows() == 1)
{
$this->update($query->row(0));
}
else return false;
}
else
{
$this->insert();
}
if ($this->arrPostData['question_no'] == 10) $this->session->unset_userdata("lastids");
}
private function update($objData)
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $objData->userid;
$objCollection->id = $objData->id;
$arrData = explode($objData->q_id);
foreach($arrData AS $key => $quizId)
{
$objQuiz = new stdClass();
$objQuiz->q_id = $quizId;
$objQuiz->answer_id = explode($objData->answer_id)[$key];
$objQuiz->time_taken = explode($objData->answer_id)[$key];
$objCollection->append($objQuiz);
}
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db
->where("id",$objCollection->id)
->update("results",$objCollection->getDbData());
}
private function insert()
{
$objCollection = new Quiz_Collection();
$objCollection->userId = $this->arrPostData['user_id'];
$objQuizFromPost = new stdClass();
$objQuizFromPost->q_id = $this->arrPostData["questionid"];
$objQuizFromPost->answer_id = $this->arrPostData['AnswerID'];
$objQuizFromPost->time_taken = $this->arrPostData['timetaken'];
$objCollection->addQuizFromPost($objQuizFromPost);
$this->db->insert("results",$objCollection->getDbData());
$this->session->set_userdata("lastids", $this->db->insert_id());
}
}
as an addition you need a Collection Object (put this below your model)
class Quiz_Collection extends Array_Object
{
public $userId = 0;
public $id = 0;
public function addQuizFromPost($objQuiz)
{
if (intval($objQuiz->q_id) > 0)
{
foreach($this AS $key => $obj)
{
if ($obj->q_id == $objQuiz->q_id)
{
$this->offsetSet($key, $objQuiz);
return true;
}
}
$this->append($objQuiz);
return true;
}
return false;
}
public function sortQuizData($objA, $objB)
{
if ($objA->q_id == $objB->q_id) return 0;
return ($objA->q_id < $objB->q_id) ? -1 : 1;
}
public function getDbData()
{
$this->uasort(array($this,"sortQuizData"));
$arrData = $this->getArrayCopy();
$arrDbData = [
"userid" => $this->userId,
"q_id" => implode(array_map(function($obj){ return $obj->q_id;},$arrData),","),
"answer_id" => implode(array_map(function($obj){ return $obj->answer_id;},$arrData),","),
"time_taken" => implode(array_map(function($obj){ return $obj->time_taken;},$arrData),","),
];
return $arrDbData;
}
}
pS: this is just an instruction how you can do that in a proper way. Pls study this code. If you still don't understand whats going on, feel free to ask.
I am working in codeigniter.I have created one function in model.The function is like this :
function pr($id)
{
//$query5 = $this->db->query("select max(to_date) as last_date from agent_print_details where agent_id = ".$id);
//$result5 = $query5->result();
$this->db->select('max(to_date) as last_date');
$this->db->from('agent_print_details');
$this->db->where('agent_id',$id);
$result = $this->db->get();
if($result->num_rows()>0)
return $result->result();
else
return "empty";
}
my controller is :
$pr_detail = $this->cashier1_model->pr($role['id']);
if($pr_detail != 0)
{
echo "nisarg";
}
else
{
echo "123";
}
when I print pr_detail then it will display output like this:
Array ( [0] => stdClass Object ( [last_date] => ) )
it will give blank data so it has to print 123 but it is display nisarg.
So What should i have to do to print 123?
If result not found just return FALSE in model file. Also use CI select_max to get max value
MODEL
$this->db->select_max('to_date','last_date');
$this->db->from('agent_print_details');
$this->db->where('agent_id', $id);
$result = $this->db->get();
if ($result->num_rows() > 0) {
return $result->result();
} else {
return FALSE;
}
CONTROLLER
$pr_detail = $this->cashier1_model->pr($role['id']);
if($pr_detail)
{
echo "nisarg";
}
else
{
echo "123";
}
you could use count function, also, do you have defined a table name in get function?
...
$result = $this->db->get('agent_print_details');
//if($result->num_rows() > 0)
if(count($result) > 0)
...
When you use $result->num_rows() > 0 you CANT use $result->result(). If u want to return these results, you need to check if its not empty first, and then query again to get results.
$this->db->select_max('to_date','last_date');
$this->db->from('agent_print_details');
$this->db->where('agent_id', $id);
$result = $this->db->get();
if ($result->num_rows() > 0) {
$this->db->select_max('to_date','last_date');
$this->db->from('agent_print_details');
$this->db->where('agent_id', $id);
$result = $this->db->get();
return $result->result();
} else {
return FALSE;
}