format to write query in codeigniter - php

I am new with codeigniter.
I have following query, each query having different table name and different where condition.
Can i make this query in single query or is it correct way to execute query.
i have to execute all this query.
$q = $this->db->where('id', $st)->update('st_info', array(
'status' => 0,
'updated_time' => $this->info_model->getTime(),
'updated_ip' => $this->info_model->getIP()
));
$q = $this->db->where('verid', $vid)->update('st_version', array(
'status' => 0,
'updated_time' => $this->info_model->getTime(),
'updated_ip' => $this->info_model->getIP()
));
$q = $this->db->where('id', $id)->update('st_raw', array(
'status' => 0,
'updated_time' => $this->info_model->getTime(),
'updated_ip' => $this->info_model->getIP()
));

Since you are using same columns for all the tables, i prefer to work with below method,
$data = array(
'status' => 0,
'updated_time' => $this->info_model->getTime(),
'updated_ip' => $this->info_model->getIP()
);
$q = $this->db->where('id', $st)->update('st_info', $data);
$q = $this->db->where('verid', $vid)->update('st_version', $data);
$q = $this->db->where('id', $id)->update('st_raw', $data);

That is correct you cannot combine all that into a single query.

Try this:
$data=array(
'status' => 0,
'updated_time' => $this->info_model->getTime(),
'updated_ip' => $this->info_model->getIP()
));
$this->db->where('id',$st);
$this->db->update('st_info', $data);
$this->db->where('verid',$vid);
$this->db->update('st_version', $data);
$this->db->where('id',$id);
$this->db->update('st_raw', $data);

Create a single function
public function update($table,$where,$data)
{
$this->db->where($where);
$this->db->update($table,$data);
}
Now call this function like this from controller
function update_call()
{
$data['status'] = 0;
$data['updated_time'] = $this->info_model->getTime();
$data['updated_ip'] = $this->info_model->getIP();
$where['id'] = $st;
$table = 'st_info';
$this->model_name->update($table,$where,$data);
unset($where);
unset($table);
$where['verid'] = $vid;
$table = 'st_version';
$this->model_name->update($table,$where,$data);
unset($where);
unset($table);
$where['id'] = $id;
$table = 'st_raw';
$this->model_name->update($table,$where,$data);
}

Related

codeigniter php Event management system.. I want to make notification when the event is created

Good Day sir. can someone help me i'm trying to code for notification. Event management system. The admin will create the event for scholars. During the process the creation of the event the admin will choose what scholarship is the event for. When the admin finish creating the event this scholars from this scholarship will automatically receive their notification. My problem is i can't insert the event_id into my notification table in the database. i don't know why my $this->db->insert_id() in $data7. the $data5 and $data6 is working
public function create_event_scholar()
{
$now = date('Y-m-d');
$start=$_POST['start_date'];
$end=$_POST['end_date'];
if(($start==$now)||$end==$now){
$event_status= "Ongoing";
}
else if(($start < $now)&&($end>$now)){
$event_status= "Ongoing";
}
else if(($start<$now)&&($end<$now)){
$event_status= "Done";
}
else {
$event_status= "Upcoming";
}
$data = array
(
'event_id' => '',
'event_title' => $this->input->post('event_title',true),
'event_desc' => $this->input->post('event_desc',true),
'start_date' => $this->input->post("start_date",true),
'end_date' => $this->input->post("end_date",true),
/*'event_status' => $event_status,*/
'event_sponsor' => $this->input->post('event_sponsor',true),
'Semester' => $this->input->post("Semester",true),
'school_year' => $this->input->post('school_year',true),
'event_for' => 'Scholar',
'start_time' => $this->input->post('start_time',true),
'venue' => $this->input->post('venue',true),
'end_time' => $this->input->post('end_time',true),
'user_id' => $this->input->post('user_id',true),
'color ' => $this->input->post('color',true)
);
$sql1= $this->db->insert('event',$data);
$earlier = new DateTime($_POST['start_date']);
$later = new DateTime($_POST['end_date']);
$diff = $later->diff($earlier)->format("%a");
$data = array(
'security_id' => "",
'event_id' =>$this->db->insert_id(),
'scholarship' =>$this->input->post('scholarship',true),
'max_attendees' =>$this->input->post('Participants',true),
'pre_reg' =>$this->input->post('pre',true),
'total_attendance'=>$diff,
'event_duration' =>$this->input->post('event_duration',true),
);
$sql2=$this->db->insert('event_security',$data,'event_id');
$data3=array(
'assign_id' => '',
'user_id' =>$this->input->post('user_id',true),
'event_id' =>$this->db->insert_id()
);
$sql3= $this->db->insert('tbl_staff_events',$data3);
$data5 = array(
'notification_id' =>'',
'subject' =>$this->input->post('event_title',true),
'body' =>"There is an event",
'event_id' =>$this->db->insert_id()
);
$this->db->insert('notification',$data5);
$subject=$this->input->post('scholarship',true);
$this->db->select('*');
$this->db->from('tbl_scholar');
$this->db->where('scholarship_id',$subject);
$get= $this->db->get()->result_array();
foreach ($get as $value) {
$data6=array(
'participants_id' => '',
'event_id' =>$this->db->insert_id(),
'user_id' =>$value['user_id']
);
$this->db->insert('participants',$data6);
}
$data7= array(
'sent_id' =>'',
'read' =>'0',
'recieve' =>'0',
'notification_id' =>$this->db->insert_id(),
'participants_id' =>$this->db->insert_id()
);
$this->db->insert('sent_notification',$data7);
if($sql1===true && $sql2===true && $sql3 === true)
{
return true;
}
else
{
return false;
}
}
This code may help you,
$sql1= $this->db->insert('event',$data);
$event_id = $this->db->insert_id();
$this->db->insert('notification',$data5);
$notification_id = $this->db->insert_id();
$this->db->insert('participants',$data6);
$participants_id = $this->db->insert_id();
$this->db->insert_id(); returns the last executed query id

How to select from 2 different table and insert to 1 table

I have a function is select from books table insert to the orders table.
Now I want to select from books and users table for insert to the orders table.
This is book table
This is the orders table
This is the users table
model
public function history($book_id){
$this->db->select('book_id,book_title,pickup,return');
$this->db->from('books');
$this->db->where('book_id', $book_id);
$query = $this->db->get();
if ( $query->num_rows() > 0 ) // if result found
{
$row = $query->result_array();
foreach($row as $values){
$data = array(
'book_id' => $values['book_id'],
'title' => $values['book_title'],
'pickup' => $values['pickup'],
'return_time' => $values['return'],
);
$this->db->insert('orders', $data);
}
return true;
}
else{
return false;
} }
You will join the tables like this
$this->db->join('users_table_name', 'users_table_name.id = books.user_id');
Everything else should work the same
for user_id u can get from session,
for example :
$data = [
'book_id' => $values['book_id'],
'user_id' => $this->session->userdata('session_name'),
'title' => $values['book_title'],
'pickup' => $values['pickup'],
'return_time' => $values['return'],
];
hopes this helps
public function insert_record($book_id, $user_id) {
$book = $this->db->select('book_id, book_title, pickup, return')
->from('books')
->where('book_id', $book_id)
->get()
->result_array();
if(!empty($book)) {
$data = array(
'book_id' => $book[0]['book_id'],
'user_id' => $user_id,
'title' => $book[0]['book_title'],
'pickup' => $book[0]['pickup'],
'return_time' => $book[0]['return'],
);
$this->db->insert('orders', $data);
}
}

Inserting data into a table returns with insertId 0

I used CodeIgniter as a framework for my development.
I am trying to insert data to a table at MySQL database.
Data is inserted as follows.
$dataArray['categoryId'] = $categoryId['id'];
$dataArray['subCategoryId'] = $subTypeId;
$dataArray['title'] = $title;
$dataArray['regionId'] = $regionId;
$dataArray['slogan'] = $slogan;
$dataArray['lastUpdated'] = date('Y-m-d H:i:s');
$dataArray['createdDate'] = date('Y-m-d H:i:s');
$dataArray['state'] = 'Unhide';
$dataArray['status'] = 'Active';
$dataArray['approval'] = 'Incompleted';
$dataArray['user_id'] = $userId;
$this->db->insert($carrentals, $dataArray);
$insertId = $this->db->insert_id();
My table is structured as in the attached image.
$insertId always returns 0 and no data is inserted into the table.
I can manually insert data into the table.
What could be wrong?
I have AUTO_INCREMENT column as id. But no data is inserted and always returns 0.
EDIT:
My actual code is
$dataArray = [
'categoryId' => $categoryId['id'],
'subCategoryId' => $subTypeId,
'title' => $title,
'regionId' => $regionId,
'slogan' => $slogan,
'lastUpdated' =>date('Y-m-d H:i:s')
];
if (empty($_POST['referenceId'])) {
$dataArray['createdDate'] = date('Y-m-d H:i:s');
$dataArray['state'] = 'Unhide';
$dataArray['status'] = 'Active';
$dataArray['approval'] = 'Incompleted';
$dataArray['user_id'] = $userId;
$this->db->insert($carrentals, $dataArray);
$insertId = $this->db->insert_id();
$responseArray = array(
'result' => $insertId,
'success' => true);
return $this->set_response($responseArray, REST_Controller::HTTP_OK);
}
Probably returning FALSE not zero. insert() returns TRUE or FALSE, check the results before proceeding
$inserted = $this->db->insert($carrentals, $dataArray);
if($inserted)
{
$responseArray = ['result' => $insertId, 'success' => true];
}
else
{
$responseArray = ['result' => NULL, 'success' => false];
}
return $this->set_response($responseArray, REST_Controller::HTTP_OK);
I don't see any problem with the way you create $dataArray.
Try replacing your $dataArray for
$dataArray = array( 'categoryId' => $categoryId['id'],
'subCategoryId' => $subTypeId,
'title' => $title,
'regionId' => $regionId,
'slogan' => $slogan,
'lastUpdated' => date('Y-m-d H:i:s'),
'createdDate' => date('Y-m-d H:i:s'),
'state' => 'Unhide',
'status' => 'Active',
'approval' => 'Incompleted',
'user_id' => $userId
);
$this->db->insert($carrentals, $dataArray);
$insertId = $this->db->insert_id();
Try to checking how is the query with $this->db->last_query();, additionally check relations (if you have it), if userId or categoryId are empty.
-- https://www.codeigniter.com/user_guide/database/helpers.html

Saving PHP variable to MySQL INT is always 0

I am having a problem passing a variable to be saved as INT in MySQL. The closest thing I could find to my issue is this question but I have already verified that I am not using single and double quotes. When I print_r($this->session->userdata('subdomain')) I see the correct subdomain id on my screen (in this case 10), but when I try passing this using $params it always save subdomain_id as 0 and I can not figure out why.
Here is Project_assignees_model:
function add_prefix_project_assignees($params)
{
$this->db->insert('prefix_project_assignees',$params);
return $this->db->insert_id();
}
Here is my Project controller (Specifically it is the $assignees array):
function edit($entry_id)
{
$this->load->library('form_validation');
$this->form_validation->set_rules('client_id','Client Id','required|integer');
$this->form_validation->set_rules('title','Project Title','required|max_length[255]');
$this->form_validation->set_rules('project_status','Project Status','required');
$this->form_validation->set_rules('project_details','Project Details','required');
$this->form_validation->set_rules('project_estimated_hours','Project Estimated Hours','required|max_length[255]');
$this->form_validation->set_rules('end','Project Deadline','required');
if($this->form_validation->run())
{
date_default_timezone_set("America/New_York");
$date = date("Y-m-d h:i:sa");
$params = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'client_id' => $this->input->post('client_id'),
'title' => $this->input->post('title'),
'project_status' => $this->input->post('project_status'),
'project_details' => $this->input->post('project_details'),
'project_last_updated' => $date,
'project_estimated_hours' => $this->input->post('project_estimated_hours'),
'start' => $this->input->post('start'),
'end' => $this->input->post('end'),
'owner_id' => get_current_user_id(),
);
$prefix_projects_id = $this->Project_model->update_prefix_projects($entry_id,$params);
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
$this->load->model('Project_assignee_model');
$insertAssignees = array();
for ($i = 0; $i < count($assignees['user_id']); $i++)
{
//Get user_id from ID
$userID = $assignees['user_id'][$i];
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
$prefix_assignees = $this->Project_assignee_model->add_prefix_project_assignees($insertAssignees[$i]);
}
//redirect('project/index');
}
else
{
$this->load->model('Client_model');
$data['prefix_clients'] = $this->Client_model->get_all_prefix_clients();
$data['prefix_projects'] = $this->Project_model->get_prefix_projects($entry_id);
$data['prefix_users'] = $this->aauth->list_users();
$this->load->model('Project_assignee_model');
$data['prefix_assignees'] = $this->Project_assignee_model->get_prefix_project_assignees($entry_id);
$this->load->view('project/edit',$data);
}
}
Why does print_r show the correct subdomain_id but when it is saved to database it saves as 0?
*******UPDATE*******
Just for reference, this works:
$assignees = array(
'subdomain_id' => 10,
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
But this does not (Even though printing the userdata for subdomain gives me 10):
$assignees = array(
'subdomain_id' => $this->session->userdata('subdomain'),
'project_id' => $entry_id,
'user_id' => $this->input->post('assignee'),
);
Sometimes I guess it just takes writing it out for others before I realize my problem. When I loop through each assignee to add them to the table I realized I was not passing the subdomain_id with it.
I had this:
$insertAssignees[$i] = array('project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch
Needed to be changed to have subdomain_id included
$insertAssignees[$i] = array('subdomain_id' => $this->session->userdata('subdomain'), 'project_id' => $entry_id, 'user_id' => $assignees['user_id'][$i]); // $insert is ready for insert_batch

How to change mysql date format using codeigniter

I am developing a website using CI and mysql. i want to change date format from yyyy-mm-dd into dd-mm-yyyy. I know that i should use date_format function. But when I try to use it, it didn't work-the date format didn't change. Also i've try to add 2nd parameter(FALSE). but, I also found problem with that, especially, when i need to query more than 1 column. Here is my code:
function __construct() {
parent::__construct();
$this->table = array(
'name' => 'article',
'coloumn' => array(
'article_id',
'article_title',
'article_content',
'article_summary',
'date_format(article_publishdate, \'%d-%M-%Y %H:%i:%s\') as article_publishdate',
'article_source',
'article_link',
'media_type',
'media_link',
'media_position',
'article_category.category_title',
),
'join' => array(
0 => array('article_category' , 'article.article_category_id=article_category.category_id', 'left'),
),
'where' => array(),
'order' => array(),
'limit' => array(),
'idkey' => 'article_id',
);
}
public function getfullbody($id)
{
$this->db->query("update article set article_view = (article_view+1) where article_id = '$id'");
$this->db->select($this->table['column'], FALSE);
if (count($this->table['join'])>0){
foreach ($this->table['join'] as $row):
if (!empty($row[2])){
$this->db->join($row[0], $row[1], $row[2]);
}
else {
$this->db->join($row[0], $row[1]);
}
endforeach;
}
$this->db->where("article_id = '$id'");
$query = $this->db->get($this->table['name']);
$data = $query;
return $data;
}
Problem: when i use date_format() with codeigniter, it didn't change the date format.
Then, how to fixed it? Thank you.
Change coloumn to column index and if you want to show date as dd-mm-yyyy use this below code
function __construct() {
parent::__construct();
$this->table = array(
'name' => 'article',
'column' => array(
'article_id',
'article_title',
'article_content',
'article_summary',
'date_format(article_publishdate, \'%d-%m-%Y\') as article_publishdate',
'article_source',
'article_link',
'media_type',
'media_link',
'media_position',
'article_category.category_title',
),
'join' => array(
0 => array('article_category' , 'article.article_category_id=article_category.category_id', 'left'),
),
'where' => array(),
'order' => array(),
'limit' => array(),
'idkey' => 'article_id',
);
}
public function getfullbody($id)
{
$this->db->query("update article set article_view = (article_view+1) where article_id = '$id'");
$this->db->select($this->table['column'], FALSE);
if (count($this->table['join'])>0){
foreach ($this->table['join'] as $row):
if (!empty($row[2])){
$this->db->join($row[0], $row[1], $row[2]);
}
else {
$this->db->join($row[0], $row[1]);
}
endforeach;
}
$this->db->where("article_id = '$id'");
$query = $this->db->get($this->table['name']);
$data = $query;
return $data;
}
Test on Code igniter 2...
('%d-%m-%Y')
in your coude
"date_format(article_publishdate, ('%d-%m-%Y')) as article_publishdate",
it's work very weel for me

Categories