In my application controller, I have a method transaction_reimburse() that receives ids as POST string values. The method's function is to get all transactions that match the ids from the database, and update them accordingly.
Controller method:
public function transaction_reimburse() {
$reimburse = array('reimburse' => 1);
$transactions = $this->Transaction_model->get_these_ids($this->input->post('ids'));
$this->Transaction_model->reimburse_these($transactions, $reimburse);
}
Model method:
function get_these_ids($ids) {
$this->db->select('tbl_user.name as uname, tbl_transactions.participant_id as pid, tbl_transactions.card_number as card_no, tbl_transactions.group as ugroup, tbl_toilet.name as utoilet, tbl_transactions.amount_paid as u_amount, tbl_transactions.toilet_price as t_price, tbl_transactions.reimburse_amount as r_amount, tbl_transactions.details as u_details');
$this->db->from('tbl_transactions');
$this->db->join('tbl_user', 'tbl_user.participant_id = tbl_transactions.participant_id', 'left');
$this->db->join('tbl_toilet', 'tbl_toilet.toilet_code = tbl_transactions.toilet_code', 'left');
$this->db->where("tbl_transactions.id IN (". $ids .")");
return $this->db->get();
}
Model method:
function reimburse_these($transactions, $reimburse) {
$this->db->select('tbl_user.name as uname, tbl_transactions.participant_id as pid, tbl_transactions.card_number as card_no, tbl_transactions.group as ugroup, tbl_toilet.name as utoilet, tbl_transactions.amount_paid as u_amount, tbl_transactions.toilet_price as t_price, tbl_transactions.reimburse_amount as r_amount, tbl_transactions.details as u_details');
$this->db->from('tbl_transactions');
$this->db->join('tbl_user', 'tbl_user.participant_id = tbl_transactions.participant_id', 'left');
$this->db->join('tbl_toilet', 'tbl_toilet.toilet_code = tbl_transactions.toilet_code', 'left');
$this->db->where("tbl_transactions.id IN (". $transactions .")");
$this->db->update($this->tbl_transaction, $reimburse);
}
However, I am getting the following error:
A PHP Error was encountered
Severity: 4096
Message: Object of class CI_DB_mysql_result could not be converted to string
Filename: models/transaction_model.php
Line Number: 450
A Database Error Occurred
Error Number: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
UPDATE `tbl_transactions` SET `reimburse` = 1 WHERE `tbl_transactions`.`id` IN ()
Filename: C:\xampp\htdocs\ipa\system\database\DB_driver.php
Line Number: 330
What I need to know is why do I get these errors?
The errors mean that your $ids variable is not in a string format (meaning: 1,2,3,4. Its probably an array). To fix it, first find out what format it is on by using print_r($ids) or var_dump($ids). Once you know the format, use PHP functions(such as implode()) to transform it into strings.
IN is looking for a set in the format e.g. (1,2,3,4).
Either make your post values adopt the format 1,2,3,4 so that when the value is included into the query it's valid or if you're sending an array use a method in PHP such as implode(',',$array) to create the desired format for binding into the query..
I have reviewed your both function and found that in both function you put tbl_transactions.id in where clause and ids is passed from post and hence there is no need to call get_these_ids to get ids, you already have ids in post array and hence instead of transactions variable, just use $this->input->post('ids') for reimburse_these functions.
if you surely want to get tbl_transactions from get_these_ids function then you need to use group_concat with group by in query of get_these_ids function and just return that concated id in get_these_ids function then it will work.
Related
i am getting data using crawl and trying to insert into database. i get abbreviations of company name and have a command to get the full form of the abbreviations. it works fine if the company name already exists in companies table, and when the command handle is run new company name is also inserted and i can get the name from the table but cannot insert the name as it shows error. here is the code:
$data['symbol']=$es[1];
$name=DB::table('companies')
->select('stock_name')
->where('stock_symbol',$data['symbol']=$es[1])
->first();
if(!empty($name->stock_name)){
$data['company_name']= $name->stock_name;
}else{
\Artisan::call("company:handle");
$name=DB::table('companies')
->select('stock_name')
->where('stock_symbol',$data['symbol']=$es[1])
->first();
$data['company_name']= $name->stock_name;
}
You can resolve it by doing
//...
$data['company_name']= $name->stock_name ?? '';
//...
Null coalescing (??) is a new operator introduced in PHP 7. This
operator returns its first operand if it is set and not NULL.
Otherwise it will return its second operand.
When I run the below query I get the following error: Invalid parameter number: mixed named and positional parameters.
$subQuery = DB::table('earliest_count')
->select('reporting_week')
->where('vendor_name', $vendorName);
$dates = DB::table('invoice')
->select('week_beginning_date', 'week_end_date')
->whereRaw(':sql BETWEEN `week_beginning_date` AND `week_end_date`', [':sql' => DB::raw("({$subQuery->toSql()})")])
->where('week_beginning_date', '<', $date)
->orderBy('week_beginning_date')
->limit(1)
->mergeBindings($subQuery)
->get();
If I replace the whereRaw with the following it works:
->whereRaw('(SELECT reporting_week FROM earliest_count WHERE vendor_name = "My Vendor") BETWEEN `week_beginning_date` AND `week_end_date`')
How can I get the subquery to work without having to write the exact query as a string?
Edit
I did try the following, and I get no errors but I don't get any results. (When I enter the subquery as a string I do get a result):
->whereRaw('? BETWEEN `week_beginning_date` AND `week_end_date`', [DB::raw("({$subQuery->toSql()})")])
Laravel doesn't use named placeholders, you should use ? for placeholders and remove the name from the parameters array.
Like this:
->whereRaw('? BETWEEN `week_beginning_date` AND `week_end_date`', [DB::raw("({$subQuery->toSql()})"])
I am having 2 tables, users and profiledetails
I am able to run Join query and access the data and send to view.
But when I am manipulation the field 'dob' (date format) in profiledetails table. No Success, Please check the code below ,
webpagesConroller:
$users = DB::table('users')
->join('profiledetails', 'users.id', '=', 'profiledetails.user_id')
->select('users.*', 'profiledetails.dob')
->get();
$age = $users->dob->diffInYears(Carbon::now());
return view('webpages.index',compact('users'))->with($age);
View:
<li class="cate_head">Age : {{ $age}}</li>
Error:
Trying to get property of non-object
I have model Profiledetails added the mutators as below,
public function getAge(){
return $this->dob->diffInYears(Carbon::now());
}
public function getDOB(){
return $this->dob->format('d-m-Y');
}
Can I not use this method on another controller for Ex- webpagesController, If yes How.
Since you are using a raw query, the data returned is not an object but an array with the data.
Also you did not limit the query, meaning it could return multiple rows.
You'll probably need to get the data from the $users as:
//with the possibily of multiple rows. Index is the row which has to be used
$users[index]['dob']
//when you are sure it only returns one row
$users[0]['dob'] // or $users['dob'] not sure as of the moment
You want to check the differences with Carbon.
So you will probably need to make a Carbon object of the dob result and check it against the Carbon::now.
$age = Carbon::createFromFormat('Y-m-d', $users[0]['dob'])->diffForHumans();
// diffForHumans() uses the local time
Note that this only gets the age for one row (the index or the first because of [0]).
If you want to do it for every row use a for or foreach where you set the $users->age for every $user. But as these are not object/models but raw data, this will not work.
Hope this helps your question a bit
This is a Noob question , but i have searched a lot with no luck.
I am returning array of objects from model to controller and i have to pass it to another model. I will have to convert it but how ?
This is my controller :
$data['customer_phoneno'] = $this->session->userdata('customer_phoneno');
$data['cid']=$this->Stylish_wizard->getCid($this->session->userdata('customer_phoneno'));
$data['bookings']=$this->Myaccount_customer->getBookings($cid);
Model :
public function getBookings($cid)
{
$this->db->where('cid', $cid);
$this->db->from('bookings');
$query = $this->db->get();
return $query->result();
}
I want to get the data from one model and use it to get some other data from another model.
I had tried passing $data['cid'] but got this error
A PHP Error was encountered
Severity: Notice
Message: Array to string conversion
Filename: database/DB_query_builder.php
Line Number: 662
Backtrace:
File: C:\xampp\htdocs\style\application\models\Myaccount_customer.php
Line: 24
Function: where
File: C:\xampp\htdocs\style\application\controllers\Myaccount.php
Line: 95
Function: getBookings
File: C:\xampp\htdocs\style\index.php
Line: 292
Function: require_once
A Database Error Occurred
Error Number: 1054
Unknown column 'Array' in 'where clause'
SELECT * FROM `bookings` WHERE `cid` = `Array`
Filename: C:/xampp/htdocs/style/application/models/Myaccount_customer.php
Line Number: 26
I tried passing
$data['cid']->cid
But its not working
When i printed $data['cid'] i got
Array ( [0] => stdClass Object ( [cid] => 8 ) )
So how do i convert it in string ?
Then you can achieve it using as
Controller
public function your_function(){
$this->load->model('folder_name/my_calling_model');//initialize that model
//your rest code
$data['my_data'] = $this->my_calling_model->my_calling_function();//your function to be called
}
You can call another model within your code as like above code,but it seems you might be having a typo within your code while passing $cid it seems to be $data['cid'] instead. So your code looks like
$data['bookings']=$this->Myaccount_customer->getBookings($data['cid']);//<----- changed from $cid to $data['cid']
Correct me if I am wrong, but I think you want to achieve this:
$data['customer_phoneno'] = $this->session->userdata('customer_phoneno');
$data['cid']=$this->Stylish_wizard->getCid($this->session->userdata('customer_phoneno'));
$data['bookings']=$this->Myaccount_customer->getBookings($data['cid']);
Make sure to pass the right array / object element.
edit:
Like I said: Make sure to pass the right array or object element. $data['cid'] contains an array. But you have to pass a String(the id). So you have to look at this array and pass the right element with your id.
In my Yii application, I have a model that represents siteconfig table and have four columns:
integer config_id,
string key,
string value,
string update_time.
I created a model using Gii (to ensure that I will not make any mistakes). I don't publish entire code here, cause this is 100% unmodified by me, standard model code generated by Gii. Since my problem is related to search, I only publish important part of generated code (the search() method):
public function search()
{
// Warning: Please modify the following code to remove attributes that
// should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('config_id',$this->config_id);
$criteria->compare('key',$this->key,true);
$criteria->compare('value',$this->value,true);
$criteria->compare('update_time',$this->update_time,true);
return new CActiveDataProvider($this, array(
'criteria'=>$criteria,
));
}
I'm trying to use generated model in normal Yii ActiveRecord search like that:
$etona = new SiteConfigurationRecord();
$crit = new CDbCriteria();
$crit->select = "value";
$crit->condition = "key=:key";
$crit->params = array(":key"=>"sitename");
$etona = $etona->find($crit);
But, instead of getting expected search results, a strange (for me) error occurs:
CDbCommand failed to execute the SQL statement: SQLSTATE[42000]:
Syntax error or access violation: 1064 You have an error in your SQL
syntax; check the manual that corresponds to your MySQL server version
for the right syntax to use near 'key='sitename' LIMIT 1' at line 1.
The SQL statement executed was: SELECT value FROM siteconfig t
WHERE key=:key LIMIT 1
Where did I go wrong?
You used key for column name, which is a reserved word in MySQL. Yii uses table alias in queries, but does not take any special care in case of reserverd word used as columns names. So, you have to take care of this by yourself.
For example:
$etona = new SiteConfigurationRecord();
$crit = new CDbCriteria();
$crit->select = "value";
$crit->condition = "t.key=:key"; // 't' is default alias
$crit->params = array(":key"=>"sitename");
$etona = $etona->find($crit);
This should solve your problem.
As #Dmitry explained, SQL doesn't allow you to use the column name key. The Yii call in the code in your answer works because Yii performs parameter binding automatically, using names other than reserved words for the parameters. And it also uses fully-qualified column names (prefixes all column name references with <tablename>., regardless of what invalid column name (reserved words) you pass the findByAttributes method.
now it works.. ^^
i just use this code...
$etona = SiteConfigurationRecord::model()->findByAttributes(array('key'=>'sitename'));
maybe i need to study activerecord more somehow...
but still i don't know why the code above doesn't work