Update a field in mysql - php

I have this code here:
$userid = Secure($_POST[ 'username' ]);
$user = $db->where('username', $userid)->getOne('users',array('id','web_device_id','is_pro'));
$is_user_matches = $db->where('user_id', $user['id'])->where('like_userid', self::ActiveUser()->id)->getOne('likes', array('id'));
$id = $db->where('user_id', self::ActiveUser()->id)->where('like_userid', $user['id'])->getValue('likes', 'id');
$saved = false;
if ($id > 0) {
$saved = $db->where('id', $id)->update('likes', array(
'user_id' => self::ActiveUser()->id,
'like_userid' => $user['id'],
'is_like' => 1,
'is_dislike' => 0,
'created_at' => date('Y-m-d H:i:s')
));
} else {
if(isUserLiked($user['id']) === false) {
$saved = $db->insert('likes', array(
'user_id' => self::ActiveUser()->id,
'like_userid' => $user['id'],
'is_like' => 1,
'is_dislike' => 0,
'created_at' => date('Y-m-d H:i:s')
));
}
}
These are the actions that occur when a user presses the LIKE button!
Now, my question is. How can I add in addition to these codes, an UPDATE for a table in mysql?
I would like that when a user gives a Like to a person, he will count automatically.
mysql_query("
UPDATE users
SET likes = likes + 1
WHERE id = '".$user['id']."'
");
I tried to add this code but I couldn't. I don't think I'm adding it where it should be. Can you show me an example please?

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 add data after comparison in codeigniter

I have two tables (mark and enroll). Mark table contains two students (ally, hassan) while Enroll table contains four students (ally, hassan, zuwena, saada).
I need to compare these two tables, then after comparison to add missing students from enroll table into mark table without duplication.
But I'm using codeigniter.
I tried this but I got errors'
$data['exam_id'] = $this->input->post('exam_id');
$data['class_id'] = $this->input->post('class_id');
$data['section_id'] = $this->input->post('section_id');
$data['subject_id'] = $this->input->post('subject_id');
$data['year'] = $this->db->get_where('settings' , array('type'=>'running_year'))->row()->description;
$query = $this->db->get_where('mark' , array(
'exam_id' => $data['exam_id'],
'class_id' => $data['class_id'],
'section_id' => $data['section_id'],
'subject_id' => $data['subject_id'],
'year' => $data['year']
))->result_array();
$query1 = $this->db->get_where('enroll', array(
'class_id' => $data['class_id'],
'section_id' => $data['section_id'],
'year' => $data['year']))->result_array();
$query3 = count($query1);
$query4 = count($query);
if ($query3 != $query4){
$students = $this->db->get_where('enroll' , array(
'class_id' => $data['class_id'] , 'section_id' => $data['section_id'] , 'year' => $data['year']))->result_array();
foreach($students as $row)
{
$data['student_id'] = $row['student_id'];
$this->db->not_like('mark' , $data);
$query5 = $this->db->from('mark');
$this->db->insert('mark' , $query5);
}
Based on your previous codes, if you want to add the missing mark data from enroll data, you could change your foreach block to :
if ($query3 != $query4){
// first get all the mark student_id data
$mark_student_id = $this->db->select('student_id')->get('mark')->result_array();
// then filter enroll data which does not contain mark student_id data
$new_students = $this->db->where( array(
'class_id' => $data['class_id'] , 'section_id' => $data['section_id'] , 'year' => $data['year']
))->where_not_in('student_id' , array_column($mark_student_id, 'student_id'))->get('enroll')->result_array();
// then insert filtered enroll data to mark table
$this->db->insert('mark' , $new_students);
you could restore the previous codes on your question
Thanks #Hasta Dhana, I have done a little changes to your answer according to my needs and to solve this error "you have to use the set method to update an entry" as follows,
if ($query3 != $query4){
// first get all the mark student_id data
$this->db->where(array('exam_id' => $data['exam_id'],'subject_id' => $data['subject_id']));
$mark_student_id = $this->db->select('student_id')->get('mark')->result_array();
if(count($mark_student_id)>0){
// then filter enroll data which does not contain mark student_id data
$new_students = $this->db->where( array(
'class_id' => $data['class_id'] , 'section_id' => $data['section_id'] , 'year' => $data['year']
))->where_not_in('student_id' , array_column($mark_student_id, 'student_id'))->get('enroll');
// then insert filtered enroll data to mark table
if($new_students->num_rows()>0){
foreach ($new_students->result_array() as $row){
$data['student_id'] = $row['student_id'];
$this->db->insert('mark' , $data);
}
}
}else {
$data1['exam_id'] = $this->input->post('exam_id');
$data1['class_id'] = $this->input->post('class_id');
$data1['section_id'] = $this->input->post('section_id');
$data1['subject_id'] = $this->input->post('subject_id');
$data1['year'] = $this->db->get_where('settings' , array('type'=>'running_year'))->row()->description;
$students = $this->db->get_where('enroll' , array(
'class_id' => $data1['class_id'] , 'section_id' => $data1['section_id'] , 'year' => $data1['year']))->result_array();
foreach($students as $row)
{
$data1['student_id'] = $row['student_id'];
$this->db->insert('mark' , $data1);
}
}
}
That is how was done, thanks.

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

Only one item can be added at a time to cart

I can only add one item to my cart at a time.
The previous item I add to the cart will just get replaced here is my method I use:
public function addcart(){
if(isset($this->session->userdata)){
$type = $this->session->userdata('type');
$username = $this->session->userdata('username');
$this->db->select('id_product ,price');
$query = $this->db->get('product', array('title'=> $this->input->post('title')));
$cart['product'] = $this->cart->contents();
if($query->num_rows() >0){
$row = $query->row();
$id = $row->id_product;
$cart['product'][$id] = array(
'id' => $row->id_product,
'qty' => $this->input->post('quantity'),
'price' => $row->price,
'name' => $this->input->post('title'),
//'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($cart['product'][$id]);
}
}
}
check what $cart['product'] = $this->cart->contents(); returns to you
if there is a problem there it probably reset your array of products and then you insert the second product and get a total cart of one product
I think you are using $this->db->get() badly, you are searching product by string, which is not "correct". What happens if you have same (title) identical products? You get the first one/second one?
please adjust your table as follows
id, title, price... 'custom fields', active
make id as autoincrement, active as boolean (so you can later turn on/off product)
Make your method accept parameters:
public function addcart( $id = FALSE ) {
if ($id === FALSE || !is_numeric($id)) {
//wrong ID do nothing or throw alert or inform user about it
redirect('');
}
if(isset($this->session->userdata)) {
$type = $this->session->userdata('type');
$username = $this->session->userdata('username');
$this->db->select('id_product ,price');
$query = $this->db->get('product', array('id' => $id, 'active' => '1'));
$cart['product'] = $this->cart->contents();
if($query->num_rows() >0) {
$row = $query->row();
$id = $row->id_product;
$cart['product'][$id] = array(
'id' => $row->id_product,
'qty' => $this->input->post('quantity'),
'price' => $row->price,
'name' => $this->input->post('title'),
//'options' => array('Size' => 'L', 'Color' => 'Red')
);
$this->cart->insert($cart['product'][$id]);
}
}
}
Happy cod(e)igniting.

Categories