Getting a results of DB query basing on rows number by function - php

This will be long.
I'm making class which will get data about teams - 5 Steam users basing on 32bit SteamIDs stored in database - 1 row = 1 team.
I want to get one result, when I specify teamid and all rows, when it's not defined(or when equals 'all'). And here starts the problem, 'cause specified team gives return, but I can't get all rows, it just gives null when var_dumped.
I have already created this method:
public static function baseData($teamid = null){
if(!empty($teamid)){
if(is_numeric($teamid)){
DB::getInstance()->get('', 'o90eprrzc3v8', ['53qwi8md3rm7', '=', $teamid]);
}
elseif($teamid == 'all'){
DB::getInstance()->getOrdered('', 'o90eprrzc3v8', '53qwi8md3rm7', 'ASC');
}
return DB::getInstance()->results();
}
return false;
}
where DB class' methods I use in Team class looks like this:
public function bquery($sql, $params = array()){
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)){
$x = 1;
if(count($params)) {
foreach($params as $param){
$this->_query->bindValue($x, $param);
$x++;
}
}
if($this->_query->execute()){
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
}
else{
$this->_error = true;
}
}
return $this;
}
public function action($action, $table, $where = null){
if(!empty($where)){
(array)$where;
if(count($where) === 3){
$operators = ['=', '>', '<', '>=', '<='];
$field = $where[0];
$operator = $where[1];
$value = $where[2];
if(in_array($operator, $operators)){
$sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?";
if(!$this->bquery($sql, array($value))->error()){
return $this;
}
}
}
return false;
}
elseif(empty($where)){
$sql = "{$action} FROM {$table}";
if(!$this->bquery($sql, null)->error()){
return $this;
}
}
}
public function get($selector, $table, $where = null){
if(empty($selector)){
if(!empty($where)){
return $this->action('SELECT *', $table, $where);
}
else{
return $this->action('SELECT *', $table);
}
}
else{
if(!empty($where)){
return $this->action('SELECT '.$selector.'', $table, $where);
}
else{
return $this->action('SELECT '.$selector.'', $table);
}
}
}
public function getOrdered($selector, $table, $order, $orderType, $where = null){
$orderType = strtoupper($orderType);
if(($selector = '') or (empty($selector))){
return $this->action('SELECT *', $table, 'ORDER BY '.$order.' '.$orderType.'');
}
else{
return $this->action('SELECT '.$selector.'', $table, 'ORDER BY '.$order.' '.$orderType.'');
}
}
public function results(){
return $this->_results;
}
public function count(){
return $this->_count;
}
And from this I want to
- loop through results
- return all variables, so I can echo them on index page
I've tried to create method for this, but until baseData() doesn't work, I can't check if it's working (it probably won't, as most of apps I write :D):
public static function getSteamData($teamid = 0){
for($teamid = 0;$teamid<(DB::getInstance()->count());$teamid++){
$result = self::baseData($teamid);
$stmid_capt = "STEAM_0:$result->stmidcapt_1:$result->stmidcapt_2";
$stmid_p2 = "STEAM_0:$result->stmidp2_1:$result->stmidp2_2";
$stmid_p3 = "STEAM_0:$result->stmidp3_1:$result->stmidp3_2";
$stmid_p4 = "STEAM_0:$result->stmidp4_1:$result->stmidp4_2";
$stmid_p5 = "STEAM_0:$result->stmidp5_1:$result->stmidp5_2";
$stmid64 = [
'capt' => convertId($result->stmidcapt_2),
'p2' => convertId($result->stmidp2_2),
'p3' => convertId($result->stmidp3_2),
'p4' => convertId($result->stmidp4_2),
'p5' => convertId($result->stmidp5_2),
];
$stmid3 = [
'capt' => convertId3($result->stmidcapt_1, $result->stmidcapt_2),
'p2' => convertId3($result->stmidp2_1, $result->stmidp2_2),
'p3' => convertId3($result->stmidp3_1, $result->stmidp3_2),
'p4' => convertId3($result->stmidp4_1, $result->stmidp4_2),
'p5' => convertId3($result->stmidp5_1, $result->stmidp5_2),
];
$profile_get[0] = Arrays::get('response→players', json_decode(file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.Arrays::get("steamapi→key").'&steamids='.$stmid64['capt']),true));
$profile_get[1] = Arrays::get('response→players', json_decode(file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.Arrays::get("steamapi→key").'&steamids='.$stmid64['p2']),true));
$profile_get[2] = Arrays::get('response→players', json_decode(file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.Arrays::get("steamapi→key").'&steamids='.$stmid64['p3']),true));
$profile_get[3] = Arrays::get('response→players', json_decode(file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.Arrays::get("steamapi→key").'&steamids='.$stmid64['p4']),true));
$profile_get[4] = Arrays::get('response→players', json_decode(file_get_contents('http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key='.Arrays::get("steamapi→key").'&steamids='.$stmid64['p5']),true));
$profile_avatar = [
'capt' => Arrays::get('0→avatarmedium', $profile_get[0]),
'p2' => Arrays::get('0→avatarmedium', $profile_get[1]),
'p3' => Arrays::get('0→avatarmedium', $profile_get[2]),
'p4' => Arrays::get('0→avatarmedium', $profile_get[3]),
'p5' => Arrays::get('0→avatarmedium', $profile_get[4]),
];
$profile_status = [
'capt' => Arrays::get('0→personastate', $profile_get[0]),
'p2' => Arrays::get('0→personastate', $profile_get[1]),
'p3' => Arrays::get('0→personastate', $profile_get[2]),
'p4' => Arrays::get('0→personastate', $profile_get[3]),
'p5' => Arrays::get('0→personastate', $profile_get[4]),
];
$profile_name = [
'capt' => escape(Arrays::get('0→personaname', $profile_get[0])),
'p2' => escape(Arrays::get('0→personaname', $profile_get[1])),
'p3' => escape(Arrays::get('0→personaname', $profile_get[2])),
'p4' => escape(Arrays::get('0→personaname', $profile_get[3])),
'p5' => escape(Arrays::get('0→personaname', $profile_get[4]))
];
}
}
I hope someone was so patient to read all of this stuff and can help me with making it work :D

Related

Online exam scores duplicating after two or more saves

I have a school web app that has an online exam feature. Students are given a number of times they can attempt the exam.
However, when a student attempts the exam two or more times and saves, the scores are duplicated in the database instead of being updated.
I will like that when a student attempts an exam again, the previous scores are overwritten not duplicated.
Controller:
public function save()
{
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$total_rows = $this->input->post('total_rows');
if (!empty($total_rows)) {
$save_result = array();
foreach ($total_rows as $row_key => $row_value) {
if (isset($_POST['radio' . $row_value])) {
$save_result[] = array(
'onlineexam_student_id' => $this->input->post('onlineexam_student_id'),
'onlineexam_question_id' => $this->input->post('question_id_' . $row_value),
'select_option' => $_POST['radio' . $row_value],
);
}
}
$this->onlineexamresult_model->add($save_result);
redirect('user/onlineexam', 'refresh');
}
} else {
}
}
Model:
public function add($data_insert)
{
$this->db->trans_begin();
if (!empty($data_insert)) {
$this->db->insert_batch('onlineexam_student_results', $data_insert);
}
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return true;
}
}
View:
<div class="exambgtop">
<h3><?php echo $exam->exam; ?></h3>
<div class="exambgright">
<div id="box_header" class="inlineblock"></div>
<button type="button" class="btn btn-info btn-sm save_exam_btn"><?php echo $this->lang->line('submit') ?> </button>
</div>
Give this a go...
Controller:
public function save()
{
$total_rows = $this->input->post('total_rows');
if (empty($total_rows)) {
redirect('user/onlineexam');
}
foreach ($total_rows as $row_value) {
if ($this->input->post('radio' . $row_value) === null) {
continue;
}
$this->onlineexamresult_model->answer(
(int) $this->input->post('onlineexam_student_id'),
(int) $this->input->post('question_id_' . $row_value),
$this->input->post('radio' . $row_value)
);
}
redirect('user/onlineexam');
}
Model:
public function answer(int $student_id, int $question_id, string $answer)
{
// Check if the student has previously answered the question
$current_answer = $this->get_answer_by_student_id($student_id, $question_id);
if (empty($current_answer)) {
return $this->db->insert('onlineexam_student_results', [
'onlineexam_student_id' => $student_id,
'onlineexam_question_id' => $question_id,
'select_option' => $answer,
'created_at' => date('Y-m-d H:i:s')
]);
}
return $this->db->update('onlineexam_student_results', [
'select_option' => $answer,
'updated_at' => date('Y-m-d H:i:s')
], [
'onlineexam_student_id' => $student_id,
'onlineexam_question_id' => $question_id
]);
}
public function get_answer_by_student_id(int $student_id, int $question_id)
{
return $this->db->get_where('onlineexam_student_results', [
'onlineexam_student_id' => $student_id,
'onlineexam_question_id' => $question_id
])->row_array();
}

update query not updating table in transactions

I m trying to get and update data at same time but after getting data transaction is rolled back, because table is not updating.
Controller -
public function addAmount()
{
$this->form_validation->set_rules('balance_id', 'Balance Id', 'required|trim');
$this->form_validation->set_rules('farmer_id', 'farmer_id', 'required|trim');
$this->form_validation->set_rules('amount', 'amount', 'required|trim');
$this->form_validation->set_rules('amount_discount', 'discount', 'required|trim');
$this->form_validation->set_rules('payment_mode', 'payment mode', 'required|trim');
if ($this->form_validation->run() == false) {
$data = array(
'amount' => form_error('amount'),
'balance_id' => form_error('balance_id'),
'farmer_id' => form_error('farmer_id'),
'amount_discount' => form_error('amount_discount'),
'payment_mode' => form_error('payment_mode'),
);
$array = array('status' => 'fail', 'error' => $data);
echo json_encode($array);
} else {
$id =$this->generate_otp();
$data = array(
'farmer_id' => $this->input->post('farmer_id'),
'balance_id' => $this->input->post('balance_id'),
'amount_paid' => $this->input->post('amount'),
'paying_date' => $this->input->post('date'),
'amount_discount' => $this->input->post('amount_discount'),
'description' => $this->input->post('description'),
'payment_mode' => $this->input->post('payment_mode'),
'payment_id' =>$id,
);
$inserted_id = $this->advance_model->amount_deposit($data);
echo '<pre>'; print_r($inserted_id); echo ("</pre>"); exit();
$array = array('status' => 'success', 'error' => '');
echo json_encode($array);
}
}
Model:
public function amount_deposit($data)
{
$this->db->trans_start(); // Query will be rolled back
$paid_amount = $data['amount_paid'];
$this->db->insert('tbl_pay_amount', $data);
$inserted_id = $this->db->insert_id();
if ($data['balance_id'] != null) {
$query = $this->db->select('balance,balance_id,reason')
->from('tbl_balance')
->where('balance_id', $data['balance_id'])
->get();
return $query->row();
if(!empty($query)){
$b =$query['balance'];
$balance =$b - $paid_amount;
}
$this->db->update('tbl_balance', array('balance' => $balance));
}
$this->db->trans_complete(); # Completing transaction
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return json_encode(array('invoice_id' => $inserted_id, 'sub_invoice_id' => 1));
}
}
When amount to be added the balance amount need to be update automatically, but now transaction is roll back because not able to update balance amount after getting it from same table, thanks in advance.
Just added foreach loop and removed return statement now it's working fine.
public function amount_deposit($data)
{
$this->db->trans_start(); // Query will be rolled back
$paid_amount = $data['amount_paid'];
$this->db->insert('tbl_pay_amount', $data);
$inserted_id = $this->db->insert_id();
if ($data['balance_id'] != null) {
$query = $this->db->select('balance,balance_id,reason')
->from('tbl_balance')
->where('balance_id', $data['balance_id'])
->get();
$result = $query->result();
}
if (!empty($result) && isset($result)) {
foreach ($result as $key => $balance_value) {
$balance_id = $balance_value->balance_id;
$balanceAmount = $balance_value->balance;
$balance = $balanceAmount - $paid_amount;
}
$this->db->where('balance_id', $balance_id);
$this->db->update('tbl_balance', array('balance' => $balance));
}
$this->db->trans_complete(); # Completing transaction
if ($this->db->trans_status() === false) {
$this->db->trans_rollback();
return false;
} else {
$this->db->trans_commit();
return json_encode(array('invoice_id' => $inserted_id, 'sub_invoice_id' => 1));
}
}

Prestashop custom module draggable sort/order

Please tell me why I have a " Declaration of BlockRealization::updatePosition($way, $position, $id) should be compatible with ModuleCore::updatePosition($id_hook, $way, $position = NULL)"
I have this code in module.php
A similar question was here
Prestashop custom admin module draggable sort/order not working?
Under my code in module.php
<?php
if (!defined('_PS_VERSION_')) exit;
class BlockRealization extends Module {
protected $_html = '';
public function __construct() {
$this->name = 'blockrealization';
$this->tab = 'front_office_features';
$this->version = '1.0.0';
$this->author = 'XXX';
$this->need_instance = 0;
$this->ps_versions_compliancy = array('min' => '1.6', 'max' => _PS_VERSION_);
$this->bootstrap = true;
parent::__construct();
$this->displayName = $this->l('Module realization');
$this->description = $this->l('Display realization on homepage.');
$this->confirmUninstall = $this->l('Are you sure you want to uninstall?');
}
public function install() {
if (!parent::install() ||
!$this->registerHook('displayHeader') ||
!$this->registerHook('home') ||
!$this->createTables()
)
return false;
return true;
}
public function uninstall() {
if (!parent::uninstall() ||
!$this->removeTable())
return false;
return true;
}
protected function createTables() {
/* Realization */
$res = (bool)Db::getInstance()->execute('
CREATE TABLE IF NOT EXISTS `'._DB_PREFIX_.'realization` (
`id_realization_slides` int(10) unsigned NOT NULL AUTO_INCREMENT,
`image_realization` varchar(255) NOT NULL,
`position` int(10) unsigned NOT NULL,
PRIMARY KEY (`id_realization_slides`, `image_realization`)
) ENGINE='._MYSQL_ENGINE_.' DEFAULT CHARSET=UTF8;
');
return $res;
}
protected function removeTable() {
if (!Db::getInstance()->Execute('DROP TABLE `'. _DB_PREFIX_ . 'realization`'))
return false;
return true;
}
public function getContent() {
$output = null;
if (Tools::isSubmit('submit'.$this->name)) {
$errors = '';
if ($_FILES) {
$helper = new HelperImageUploader('realization_img');
$files = $helper->process();
if ($files) {
foreach ($files as $file) {
if (isset($file['save_path'])) {
if (!ImageManager::checkImageMemoryLimit($file['save_path']))
$errors = Tools::displayError('Limit');
if (!$errors) {
if (!ImageManager::resize($file['save_path'], dirname(__FILE__) . '/img/' . $file['name']))
$errors = Tools::displayError('error');
else {
$previous_file = Configuration::get('realization_img');
$file_path = dirname(__FILE__) . '/img/' . $previous_file;
if (file_exists($file_path))
unlink($file_path);
$realization['image_realization'] = $file['name'];
$realization['position'] = count($this->getAll());
if (!Db::getInstance()->insert('realization', $realization))
$errors = Tools::displayError('error');
}
}
unlink($file['save_path']);
}
}
}
}
if ($errors)
$output .= $this->displayError($errors);
else
$output .= $this->displayConfirmation($this->l('Settings updated'));
}
$output .= $this->generateList();
$output .= $this->displayForm();
return $output;
}
public function displayForm() {
// Init Fields form array
$fields_form[0]['form'] = array(
'legend' => array(
'title' => $this->l('Add the realization'),
),
'input' => array(
array(
'type' => 'file',
'label' => $this->l('Image:'),
'name' => 'realization_img',
'hint' => $this->l('Upload image for contact:'),
)
),
'submit' => array(
'title' => $this->l('Save'),
'class' => 'btn btn-default pull-right'
)
);
$helper = new HelperForm();
// Module, token and currentIndex
$helper->module = $this;
$helper->name_controller = $this->name;
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
// Title and toolbar
$helper->title = $this->displayName;
$helper->show_toolbar = true; // false -> remove toolbar
$helper->toolbar_scroll = true; // yes - > Toolbar is always visible on the top of the screen.
$helper->submit_action = 'submit'.$this->name;
$helper->toolbar_btn = array(
'save' =>
array(
'desc' => $this->l('Save'),
'href' => AdminController::$currentIndex.'&configure='.$this->name.'&save'.$this->name.
'&token='.Tools::getAdminTokenLite('AdminModules'),
),
'back' => array(
'href' => AdminController::$currentIndex.'&token='.Tools::getAdminTokenLite('AdminModules'),
'desc' => $this->l('Back to list')
)
);
// Load current value
$helper->tpl_vars = array(
'fields_value' => array(
'realization_img' => Configuration::get('realization_img')
)
);
return $helper->generateForm($fields_form);
}
public function generateList() {
$content = $this->getAll();
$fields_list = array(
'id_realization_slides' => array(
'title' => 'ID',
'align' => 'center',
'class' => 'fixed-width-xs',
),
'image_realization' => array(
'title' => $this->l('Image'),
'orderby' => false,
'search' => false
),
'position' => array(
'title' => $this->l('Position'),
'position' => 'position' ,
'orderby' => false,
'search' => false
),
);
$helper = new HelperList();
$helper->shopLinkType = '';
$helper->actions = array('edit', 'delete');
$helper->module = $this;
$helper->listTotal = count($content);
$helper->identifier = 'id_realization_slides';
$helper->title = $this->l('Realizations');
$helper->table = $this->name;
$helper->imageType = 'jpg';
$helper->orderBy = 'position';
$helper->orderWay = 'asc';
$helper->position_identifier = 'id_realization_slides';
$helper->token = Tools::getAdminTokenLite('AdminModules');
$helper->currentIndex = AdminController::$currentIndex.'&configure='.$this->name;
return $helper->generateList($content, $fields_list);
}
public function getAll() {
return Db::getInstance()->ExecuteS('
SELECT *
FROM '._DB_PREFIX_.'realization
');
}
public function ajaxProcessUpdatePositions()
{
$way = (int)Tools::getValue('way');
$id_quicklinks = (int)Tools::getValue('id');
$positions = Tools::getValue('realization_slides');
if (is_array($positions))
foreach ($positions as $position => $value)
{
$pos = explode('_', $value);
if (isset($pos[2]) && (int)$pos[2] === $id_velcroquicklinks)
{
if (isset($position) && $this->updatePosition($way, $position, $id_quicklinks))
echo 'ok position '.(int)$position.' for id '.(int)$pos[1].'\r\n';
else
echo '{"hasError" : true, "errors" : "Can not update id '.(int)$id_quicklinks.' to position '.(int)$position.' "}';
break;
}
}
}
public function updatePosition($way, $position, $id)
{
if (!$res = Db::getInstance()->executeS('
SELECT `id_realization_slides`, `position`
FROM `'._DB_PREFIX_.'realization`
ORDER BY `position` ASC'
))
return false;
foreach ($res as $quicklinks)
if ((int)$quicklinks['id_realization_slides'] == (int)$id)
$moved_quicklinks = $quicklinks;
if (!isset($moved_quicklinks) || !isset($position))
return false;
return (Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'realization`
SET `position`= `position` '.($way ? '- 1' : '+ 1').'
WHERE `position`
'.($way
? '> '.(int)$moved_quicklinks['position'].' AND `position` <= '.(int)$position
: '< '.(int)$moved_quicklinks['position'].' AND `position` >= '.(int)$position.'
'))
&& Db::getInstance()->execute('
UPDATE `'._DB_PREFIX_.'realization`
SET `position` = '.(int)$position.'
WHERE `id_realization_slides` = '.(int)$moved_quicklinks['id_quicklinks']));
}
public function hookHome($params) {
return $this->display(__FILE__, "views/templates/hook/realization.tpl");
}
Because you extend the class Module and it already has the same method which you basically override. And in PHP 7+ if you want to override or extend method you have to declare the same parameters(even if they have default values in the parent class method) and the same access level. So you just need to follow the rule and use the same declaration or you can rename your method if it's not necessary to override/extend the parent class one(and it seems so)

getting multiple customer details In codeigniter

i have written this code to receive data from the Android device. it was inserted just one customer data I need to receive multiple customer details if app goes offline. but it was inserting one data into DB in offline mode also.how can i change this for multiple customer data insertions.
function index_post($customerID = false) {
if ($customerID) {
//update the record
$updateData = array();
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
foreach ($allowedparams as $k => $v) {
if (!$this->IsNullOrEmptyString($this->post($k, true))) {
$updateData[$v] = $this->post($k, true);
}
}
if ($this->model_customer->update($customerID, $updateData)) {
$data = array('status' => true, 'messsage' => 'cusotmer updated succesfully');
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'messsage' => 'cusotmer failed to update.');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
} else {
//insert the record
$allowedparams = array('streetid' => 'streetid', 'name' => 'name', 'mobile' => 'mobile', 'adhaar' => 'adhaar', 'profession' => 'profession', 'address' => 'address', 'pincode' => 'pincode', 'cycle' => 'cycle', 'nearby' => 'nearby', 'paddress' => 'paddress', 'isOwned' => 'isOwned');
$requiredParam = array('streetid', 'name', 'mobile', 'cycle');
$insertdata = array();
foreach ($allowedparams as $k => $v) {
if (in_array($k, $requiredParam)) {
//check if its not null
if ($this->post($k) == null || trim($this->post($k)) == '') {
$data = array('status' => false, 'message' => $k . ' parameter missing or empty');
$http_code = REST_Controller::HTTP_BAD_REQUEST;
break;
}
}
$insertData[$v] = $this->post($k, true);
}
if ($customerID = $this->model_customer->create($insertData)) {
$data['customerID'] = $this->_frameCustomer2($this->model_customer->get($customerID)); //you need to put
$http_code = REST_Controller::HTTP_OK;
} else {
$data = array('status' => false, 'message' => 'unable to create customer');
$http_code = REST_Controller::HTTP_INTERNAL_SERVER_ERROR;
}
}
$this->response($data, $http_code);
}
private function _frameCustomer2($c) { //get value from index_get
$data = array();
$data['id'] = $c->id;
$data['name'] = $c->name;
$data['street'] = array('id' => $c->streetid);
$data['creationDate'] = $c->creationdate;
$data['mobile'] = $c->mobile;
$data['adhaar'] = $c->adhaar;
$data['profession'] = $c->profession;
$data['isOwned'] = ($c->isOwned == 1) ? true : false;
$data['address'] = $c->address;
$data['pincode'] = $c->pincode;
$data['status'] = $c->status;
$data['cycle'] = $c->cycle;
$data['balance'] = $c->balance;
$data['creditAvailable'] = $c->creditbalance;
$data['nearby'] = $c->nearby;
$data['accountNumber'] = $c->accountnumber;
$data['permanentAddress'] = $c->paddress;
$data['lastVisit'] = $this->model_customer->lastVisit($c->id);
return $data;
}
and my part of model function is
function create($insertdata = array()) { //new customer insert
if ($this->db->insert('customer', $insertdata)) {
return $this->db->insert_id();
} else {
return false;
}
}
function update($customerID = 0, $updateData = array()) {
$this->db->where('id', $customerID);
if ($this->db->update('customer', $updateData) && $this->db->affected_rows() == 1) {
return true;
} else {
return false;
}
Instead of customer Id, you can ask the mobile developers to send data in the form of array. In both online and offline. In case of online there will be just one element in the request array.
function index_post() {
$request_data = $this->request->body;
foreach($request_data as $key => $value)
{
//Check if customer id is present
if(Customer present)
{
Update the record
} else {
Insert the record
}
}
}

Codeigniter multiple where condition

I have a problem i only want to select a specific row/s with user_id = $this->session->id , status = 4 hours, 8 hours and work from home.
EDIT:
all my status is
Work From Home
8 hours
4 hours
Vacation Leave
Sick Leave
but what happened is it only returns all the Work From Home of the specific user_id and not included the 4 hours and 8 hours status
Controller
$order_by = "id desc";
$where = ['user_id' => $this->session->id,'status' => '4 hours', 'status' => '8 hours','status' => 'Work From Home'];
$this->Crud_model->fetch('record',$where,"","",$order_by);
MODEL
public function fetch($table,$where="",$limit="",$offset="",$order=""){
if (!empty($where)) {
$this->db->where($where);
}
if (!empty($limit)) {
if (!empty($offset)) {
$this->db->limit($limit, $offset);
}else{
$this->db->limit($limit);
}
}
if (!empty($order)) {
$this->db->order_by($order);
}
$query = $this->db->get($table);
if ($query->num_rows() > 0) {
return $query->result();
}else{
return FALSE;
}
}
Try the following:
Controller:
$order_by = "id desc";
$where = ['user_id' => $this->session->id];
$where_in = ['name' => 'status', 'values' => ['4 hours', '8 hours', 'Work From Home']];
$this->Crud_model->fetch('record',$where,"","",$order_by, $where_in);
Model:
public function fetch($table,$where="",$limit="",$offset="",$order="", $where_in = false){
if (!empty($where)) {
$this->db->where($where);
}
if (!empty($limit)) {
if (!empty($offset)) {
$this->db->limit($limit, $offset);
}else{
$this->db->limit($limit);
}
}
if (!empty($order)) {
$this->db->order_by($order);
}
if($where_in)
{
$this->db->where_in($where_in['name'], $where_in['values']);
}
$query = $this->db->get($table);
if ($query->num_rows() > 0) {
return $query->result();
}else{
return FALSE;
}
}
This uses where_in functionality to get all records for those status values.
Associate Array method:
$array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
Or if you want to do something other than = comparison
$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
$this->db->where($array);

Categories