Codeigniter multiple where condition - php

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

Related

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

Insert to db in an iterative way

I want to insert to my database payment table that should be done in this way.
The payment table that I have includes both group_id and member_id as a foreign key related to the table groups and member respectively.
What I want to do is once I hit the button "Pay" it should insert for each and every member_id as a row in the payment table.
Here is my code..
In my controller I have
public function create_action()
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$this->load->model('Member_model');
$memberid = $this->Member_model->paymember();
foreach ($memberid->result_array() as $id){
$memberid[] = $id;
$data = array(
'group_id' => $this->input->post('group_id',TRUE),
'member_id' => $memberid,
'paid_by' => $this->input->post('paid_by',TRUE),
'from_date' => $this->input->post('from_date',TRUE),
'to_date' => $this->input->post('to_date',TRUE),
'amount' => $this->input->post('amount',TRUE),
'reference_number' => $this->input->post('reference_number',TRUE),
//'last_updated_by' => $this->input->post('last_updated_by',TRUE),
//'last_update_time' => $this->input->post('last_update_time',TRUE),
);
}
$this->Payment_model->insert($data);
$this->session->set_flashdata('message', 'Record Created Successfully!');
redirect(site_url('payment'));
}
}
And in my model which is the Member_model I've included in the controller..
function paymember(){
$data= array();
$this->db->where('group_id',$this->input->post('group_id'));
$memberid = $this->db->get('member');
if ($memberid->num_rows() > 0) {
foreach ($memberid->result_array() as $row){
$data[] = $row;
}
}
}
Please help me out. Thank you.
Now I've solved the problem.
In my controller there I have got the array value from the model...
public function create_action()
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$this->load->model('Member_model');
$memberid = $this->Member_model->paymember();
if (count($memberid)) {
foreach ($memberid as $id) {
$data = array(
'group_id' => $this->input->post('group_id',TRUE),
'member_id' => $id,
'paid_by' => $this->input->post('paid_by',TRUE),
'from_date' => $this->input->post('from_date',TRUE),
'to_date' => $this->input->post('to_date',TRUE),
'amount' => $this->input->post('amount',TRUE),
'reference_number' => $this->input->post('reference_number',TRUE),
'last_updated_by' => $this->session->userdata('username'),
//'last_update_time' => $this->input->post('last_update_time',TRUE),
);
$this->Payment_model->insert($data);
echo $data;
}
}
$this->session->set_flashdata('message', 'Record Created Successfully!');
redirect(site_url('payment'));
}
}
Also on my previous model paymember method there was a problem which its not returning any result so I've fixed that with this code....
function paymember(){
$data= array();
$this->db->where('group_id',$this->input->post('group_id'));
$query = $this->db->get('member');
if ($query->num_rows() > 0) {
foreach ($query->result_array() as $row){
$data[] = $row['member_id'];
}
}
$query->free_result();
return $data;
}
Thank you for ur support!

Symfony Doctrine take the most recent date in where close

I would like to make a query which call the most recent date in the same table in a where close.
$query = $this->createQueryBuilder('a')
->select('a.amount')
->where('a.product = :productId')
->andWhere('a.id = :id'),
$recentDate = null;
if($date === null){
$recentDate = $this->createQueryBuilder('a')
->select($query->expr()->max('a.date'))->getQuery()->getResult();
$query->andWhere('a.date = :recentDate');
}else{
$query->andWhere('a.date = :date');
}
$query->setParameters(array(
'productId' => $productId,
'id' => $id,
'date' => $date,
'recentDate' => $recentDate,
));
return $query;
but I have this issue:
Invalid parameter number: number of bound variables does not match number of tokens
Just name your "date" parameter and "recentDate" parameter with the same name, they couldn't be in your request together and pass only this unique parameter in your setParameters()
$query = $this->createQueryBuilder('a')
->select('a.amount')
->where('a.product = :productId')
->andWhere('a.id = :id')
->andWhere('a.date = :date');
if($date === null){
$date = $this->createQueryBuilder('a')
->select($query->expr()->max('a.date'))->getQuery()->getResult();
}
$query->setParameters(array(
'productId' => $productId,
'id' => $id,
'date' => $date
));
return $query;
Try this:
$query->setParameters(array(
'productId' => $productId,
'id' => $id
));
if($date === null) {
$query->setParameter(':recentDate', $recentDate);
} else {
$query->setParameter(':date', $date);
}
The recentDate parameter isn't a part of the query if $date != null and vice versa so isn't the date parameter.
Maybe there's a more elegant way to build this query?
kind regards
Joe
You're providing 4 parameters to a query that only has 3.
$query = $this->createQueryBuilder('a')
->select('a.amount')
->where('a.product = :productId')
->andWhere('a.id = :id'),
$recentDate = null;
if($date === null){
$recentDate = $this->createQueryBuilder('a')
->select($query->expr()->max('a.date'))->getQuery()->getResult();
$query->andWhere('a.date = :recentDate');
}else{
$query->andWhere('a.date = :date');
}
$query->setParameters(array(
'productId' => $productId,
'id' => $id,
));
if($date === null){
$query->setParameter('recentDate', $recentDate);
}else{
$query->setParameter('date', $date);
}

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

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

How to create multiple conditioner login in codeigniter

my model is here.....but i need to select status of admin ....... but
i m new in codeigniter....and don't no how to select... my need is...
select admin whole detail from table on condition admin status =
active and id=1...
my model is :
public function login($value) {
$query = $this->db->get_where('tbl_admin', $value, 1, 'active');
if ($query->num_rows() > 0) {
$row = $query->row_array();
$sess_arr = array(
'admin_user' => $row['fld_admin_username'],
'adm_key' => $row['fld_admin_key'],
'admin_type' => $row['fld_admin_type'],
'admin_id' => $row['fld_admin_id'],
'admin_logged_in' => TRUE
);
$this->session->set_userdata($sess_arr);
//echo "<pre>";print_r($this->session->all_userdata());exit;
}
else{
$this->session->set_flashdata('error', 'Invalid username/password');
redirect('adminzone');
}
}
The correct syntax for the first line would be:
$query = $this->db->get_where('tbl_admin', array('id' => 1, 'status' => 'active'));
I.e. The second parameter to get_where is an associative array of fields and their values..
Edit: Or perhaps it should be
$query = $this->db->get_where('tbl_admin', array('id' => $value, 'status' => 'active'));
(I am not sure what the $value variable is for here).

Categories