Related
i want to search the stock till a particular date. User will fill this date form. The first page where user go to input the date field is _formtilldate.
Controller action -
public function actionIndex3() {
//$enddate = '2018-03-01';
$searchModel1 = new SellitemSearch();
$dataProvider1 = $searchModel1->search ( Yii::$app->request->queryParams );
//$searchModel2 = new PuritemtilldateSearch();
//$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render ( '_formtilldate' , [
'model1' => $searchModel1 ,
//'enddate' => $enddate,
//'model2' => $searchModel2,
//'searchModel1' => $searchModel2,
] );
}
And the form field
<?php
$form = ActiveForm::begin ( [
'id' => 'form-id' ,
'action' => [ '/stock/sellitem/stocktilldate' , 'enddate' => $model1->enddate ] ,
'method' => 'get' ,
'enableClientScript' => false ,
] );
?>
<?=
$form->field ( $model1 , 'enddate' )->widget (
DatePicker::className () , [
// inline too, not bad
'options' => [ 'placeholder' => 'End Date ...' , 'id' => 'enddate1' ] ,
'inline' => false ,
//'id' => 'startdate1',
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true ,
'todayHighlight' => true ,
'format' => 'yyyy-mm-dd'
]
] );
?>
On clicking on the submit button, the search query runs -
Controller Action -
public function actionStocktilldate( $enddate ) {
//$enddate = '2018-03-01';
$searchModel1 = new SellitemtilldateSearch();
$dataProvider1 = $searchModel1->search ( Yii::$app->request->queryParams );
//$searchModel2 = new PuritemtilldateSearch();
//$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render ( 'indexstocktilldate' , [
//'enddate' => $enddate,
'searchModel1' => $searchModel1 ,
'dataProvider1' => $dataProvider1 ,
//'searchModel2' => $searchModel2,
//'dataProvider2' => $dataProvider2,
] );
}
Search Model -
public function search( $params , $enddate ) {
//$query = Sellitem::find();
$subQuery1 = (new Query() )->select ( [ 'pi_upc' , 'sum(pi_qty) as purchased' ] )->from ( 'puritem' )->leftJoin ( 'pursum' , 'pursum.ps_id = puritem.psi_id' )->andwhere ( [ '<' , 'pursum.ps_date' , $enddate ] )->groupby ( 'pi_upc' );
$subQuery2 = (new Query() )->select ( [ 'si_iupc' , 'sum(si_qty) as sold' ] )->from ( 'sellitem' )->leftJoin ( 'sellsum' , 'sellsum.ss_id = sellitem.si_ssid' )->andwhere ( [ '<' , 'sellsum.ss_date' , $enddate ] )->groupby ( 'si_iupc' );
$subQuery3 = (new Query() )->select ( [ 'i_upc' , 'i_category' , 'i_brand' , 'i_desc' , 'i_unit' , 'i_buyprice' , 'coalesce(p.purchased,0) as purchased' ] )->from ( 'item' )->leftJoin ( [ 'p' => $subQuery1 ] , 'p.pi_upc = i_upc' );
$query = (new Query() )->select ( [ 'tp.i_upc as upc' , 'tp.i_category as category' , 'tp.i_brand as brand' , 'tp.i_desc as description' , 'tp.i_unit as unit' , 'tp.purchased as purchased' , 'coalesce(ts.sold,0) as sold' , '(coalesce(purchased,0) - coalesce(sold,0)) as stock' , 'tp.i_buyprice as rate' , 'round(((coalesce(purchased,0) - coalesce(sold,0))*tp.i_buyprice),2) as value' ] )->from ( [ 'tp' => $subQuery3 ] )->leftJoin ( [ 'ts' => $subQuery2 ] , 'ts.si_iupc = tp.i_upc' );
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query ,
'pagination' => [
'pageSize' => 10000000000 ,
] ,
]);
......
}
Now, in the url I can see the parameter got passed -
http://localhost/chayanika/frontend/web/index.php?r=stock%2Fsellitem%2Fstocktilldate&SellitemSearch%5Benddate%5D=2018-08-13
But, I'm getting error -
Bad Request (#400)
Missing required parameter: enddate
I'm not getting where I'm missing it.
I made a bit progress here -
I just learned that the date I'm getting in the URL is coming from the Action in the form. But it's not of much use so far.
If I change the controller action a bit, I get a result -
public function actionStocktilldate() {
$enddate = date ( 'Y-m-d' );
//$enddate = yii::$app->request->get('enddate');
//var_dump($enddate);
$searchModel1 = new SellitemtilldateSearch();
$dataProvider1 = $searchModel1->search ( Yii::$app->request->queryParams , $enddate );
//$searchModel2 = new PuritemtilldateSearch();
//$dataProvider2 = $searchModel2->search(Yii::$app->request->queryParams);
return $this->render ( 'indexstocktilldate' , [
//'enddate' => $enddate,
'searchModel1' => $searchModel1 ,
'dataProvider1' => $dataProvider1 ,
//'searchModel2' => $searchModel2,
//'dataProvider2' => $dataProvider2,
] );
}
Please tell me how can I pass the date collected by the form to this controller.
In your url, I don't see enddate param, I just see:
frontend/web/index.php?r=stock/sellitem/stocktilldate&SellitemSearch[enddate]=2018-08-13"
It is SellitemSearch[enddate], not enddate
You should modify your url to
frontend/web/index.php?r=stock/sellitem/stocktilldate&enddate=2018-08-13"
or remove $enddate param from actionStocktilldate function.
How is action parameter treated in ActiveForm.
Query parameters in the action are ignored for GET method. We use
hidden fields to add them back Hidden inputs are created and they are
submitted so your form action goes to the right place.
So if you look into the form source from your browser there is a hidden input created with the name enddate which will be submitted automatically.
<form id="w0" action="http://localhost/chayanika/frontend/web/index.php?r=/stock/sellitem/stocktilldate" method="get">
<input type="hidden" name="enddate" value="2018-03-01"><button type="submit">Submit</button>
</form>
Reason
But in your case, it isn't submitting because there isn't any hidden field being created. Why? because the assignment of your $model->enddate is returning null. Make sure there is a valid timestamp or date string saved.
Track
Go to line 395 of \yii\web\UrlManager function createUrl($params).
If you are using enablePrettyUrl=>true then it will enter the first check and in the foreach it appends the query string params as key where value!==null.
if($this->enablePrettyUrl){
$cacheKey = $route . '?';
foreach($params as $key => $value){
if($value !== null){
$cacheKey .= $key . '&';
}
}
if you are using enablePrettyUrl=>false then it will skip to the last section
$url = "$baseUrl?{$this->routeParam}=" . urlencode($route);
if(!empty($params) && ($query = http_build_query($params)) !== ''){
$url .= '&' . $query;
}
return $url . $anchor;
and there it will fail the check if(!empty($params) && ($query = http_build_query($params)) !== ''){ as http_build_query($params) returns empty string for an array having a key with null value.
So make sure you have a date save and the current model does not have the date saved in database as null
Hi I am using codeigniter.I need to get the last inserted id and increment it and use it in my view page,
My controller code:
public function add_tickets()
{
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
$insert_id = $this->billing_model->store_bill($data_to_store);
/*Here I am tring to get the last inserted id*/
for ($i = 0; $i < count($pid_array); $i++) {
if(isset($pid_array[$i])&& $pid_array[$i]!=""){
$data_to_store = array(
'id' => $insert_id +1,
'employee' => $emp_array[$i],
'start_time' => $start_array[$i],
'pid' => $pid_array[$i],
'total' => $total_array[$i],
'status' => $button_status,
);
$this->billing_model->store_bill($data_to_store);
}
}
$data['ticket_new_id'] = $data_to_store['id'];
$data['bill']=$this->billing_model->get_bill();
$data['main_content'] = 'admin/billing/list';
$this->load->view('includes/template', $data);
}
This is my controller function where I insert my bill.
Here is my model function,
function store_bill($data)
{
$insert = $this->db->insert('bill', $data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
Here I am using $this->db->insert_id() to get the last inserted id.
I am getting a error like this,
You must use the "set" method to update an entry.
Filename: C:\xampp\htdocs\elfanto\elfanto_billing\system\database\DB_active_rec.php
Line Number: 1174
Can someone help me? Thanks in advance
I think this is your solution:
<?php
public function add_tickets()
{
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
/*beore inserting first get the last ID of the table*/
$this->db->select('*');
$this->db->from('bill');
$this->db->order_by('id','desc');
$result = $this->db->get()->result();
$last_id = $result[0]->id;//This is the last ID of the table
/*now insert the data with incremented ID and send it to your view */
$data_to_store = array(
'id' => $insert_id +1,
'employee' => $emp_array,
'start_time' => $start_array,
'pid' => $pid_array,
'total' => $total_array,
'status' => $button_status,
);
$this->billing_model->store_bill($data_to_store);
$insert_id = $last_id + 1;//this will be your last inserted ID
$data['ticket_new_id'] = $insert_id ;
$data['bill']=$this->billing_model->get_bill();
$data['main_content'] = 'admin/billing/list';
$this->load->view('includes/template', $data);
}
For more reference how to get last ID using codeigniter check this
I have check your code not initialize the variable
$status = $this->input->post("status_button");
$emp_array = $this->input->post("employee");
$start_array = $this->input->post("start_time");
$pid_array = $this->input->post("pid");
$total_array = $this->input->post("total");
if($status == "leave_open")
{
$button_status="open";
}
else
{
$button_status="";
}
// $data_to_store is not initialized and you are trying to store the value that's why it give you error
$insert_id = $this->billing_model->store_bill($data_to_store);
I want execute this query like
UPDATE `eventinfo` SET `Status` = '0' WHERE `EventDatetime`< `2015-05-12 01:17:23`.
I tried it in different ways like this
$whereClause = 'EventDatetime'.'<'.$check_date;
$this->db->where($whereClause);
but I failed.What is the correct way.
Different way to do this :
$data = array( 'status' => '0', );
$this->db->where('EventDatetime <', '2015-05-12 01:17:23');
$this->db->update('eventinfo', $data);
Using codeigniter way for less then and greater then
$this->db->set('Status',0);
$this->db->where('EventDatetime <', '2015-05-12 01:17:23');
$this->db->update('eventinfo');
You need quotes around dates in that format.
UPDATE `eventinfo`
SET `Status` = '0'
WHERE `EventDatetime`< '2015-05-12 01:17:23'
;
This is how you can do it
$data = array( 'Status' => '0', );
$this->db->where('EventDatetime <', '2015-05-12 01:17:23');
$this->db->update('eventinfo', $data);
NOTE:
Note the space between 'EventDatetime' and '<', if there is no space, you will get an error
there are many ways to do so
$data = array( 'status' => '0', );
$whereClass="eventdatetime < '2015-05-12 01:17:23'";
$this->db->where($whereClass,NULL,FALSE);
//or $this->db->where('eventdatetime < ' ,'2015-05-12 01:17:23');
$this->db->update('eventinfo', $data);
if still got error then there must database error ,may be a missing record or something
I have an insert query (active record style) used to insert the form fields into a MySQL table. I want to get the last auto-incremented id for the insert operation as the return value of my query but I have some problems with it.
Inside the controller:
function add_post(){
$post_data = array(
'id' => '',
'user_id' => '11330',
'content' => $this->input->post('poster_textarea'),
'date_time' => date("Y-m-d H:i:s"),
'status' => '1'
);
return $this->blog_model->add_post($post_data);
}
And inside model:
function add_post($post_data){
$this->db->trans_start();
$this->db->insert('posts',$post_data);
$this->db->trans_complete();
return $this->db->insert_id();
}
I get nothing as the return of the add_post in model
Try this
function add_post($post_data){
$this->db->insert('posts', $post_data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
In case of multiple inserts you could use
$this->db->trans_start();
$this->db->trans_complete();
A transaction isn't needed here, this should suffice:
function add_post($post_data) {
$this->db->insert('posts',$post_data);
return $this->db->insert_id();
}
$id = $this->db->insert_id();
From the documentation:
$this->db->insert_id()
The insert ID number when performing database inserts.
Therefore, you could use something like this:
$lastid = $this->db->insert_id();
Using the mysqli PHP driver, you can't get the insert_id after you commit.
The real solution is this:
function add_post($post_data){
$this->db->trans_begin();
$this->db->insert('posts',$post_data);
$item_id = $this->db->insert_id();
if( $this->db->trans_status() === FALSE )
{
$this->db->trans_rollback();
return( 0 );
}
else
{
$this->db->trans_commit();
return( $item_id );
}
}
Source for code structure: https://codeigniter.com/user_guide/database/transactions.html#running-transactions-manually
It is worth saying that the other answers relate to Codeigniter version 3. The answer in Version 4 (found https://codeigniter.com/user_guide/database/helpers.html) is to use $this->db->insertID()
because you have initiated the Transaction over the data insertion so,
The first check the transaction completed or not. once you start the transaction, it should be committed or rollback according to the status of the transaction;
function add_post($post_data){
$this->db->trans_begin()
$this->db->insert('posts',$post_data);
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){
$this->db->trans_rollback();
return 0;
}else{
$this->db->trans_commit();
return $this->db->insert_id();
}
}``
in the above, we have committed the data on the successful transaction even you get the timestamp
Just to complete this topic:
If you set up your table with primary key and auto increment you can omit the process of manually incrementing the id.
Check out this example
if (!$CI->db->table_exists(db_prefix() . 'my_table_name')) {
$CI->db->query('CREATE TABLE `' . db_prefix() . "my_table_name` (
`serviceid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(64) NOT NULL,
`hash` varchar(32) NOT NULL,
`url` varchar(120) NOT NULL,
`datecreated` datetime NOT NULL,
`active` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=" . $CI->db->char_set . ';');
Now you can insert rows
$this->db->insert(db_prefix(). 'my_table_name', [
'name' => $data['name'],
'hash' => app_generate_hash(),
'url' => $data['url'],
'datecreated' => date('Y-m-d H:i:s'),
'active' => $data['active']
]);
**Inside Model**
function add_info($data){
$this->db->insert('tbl_user_info',$data);
$last_id = $this->db->insert_id();
return $last_id;
}
**Inside Controller**
public function save_user_record() {
$insertId = $this->welcome_model->save_user_info($data);
echo $insertId->id;
}
You must use $lastId = $this->db->insert_id();
i tried to make option update three table with one execution for my CI with sql there, but why its still error?
this is the error warning:
A Database Error Occurred
Error Number: 1062
Duplicate entry '0' for key 1
UPDATE `t_publisher` SET `id_publisher` = NULL, `publisher` = NULL, `artis` = NULL, `id_label` = NULL WHERE `id_publisher` = '113'
this is the code:
function update($id_user=null)
{
if (($this->input->post('submit') == 'Update')){
$user=$this->input->post('username');
$pass=$this->input->post('userpassword');
$ussta=$this->input->post('userstatus');
$usty=$this->input->post('usertype');
$data = array(
'user_name' => $user,
'user_pass' => $pass,
'user_status' => $ussta,
'user_type' => $usty);
$this->db->where('user_id', $this->input->post('id'), $data);
$this->db->update("t_user",$data);
$data1 = array(
'id_publisher' => $id_publis,
'publisher' => $publis,
'artis' => $ar,
'id_label' => $id_lab);
$this->db->where('id_publisher', $this->input->post('id'), $data);
$this->db->update("t_publisher",$data1);
echo $this->db->last_query();
die();
$data2 = array(
'id_label' => $id_lab,
'label' => $label);
$this->db->where('id_label', $this->input->post('id'), $data);
$this->db->update("t_label",$data2);
echo $this->db->last_query();
die();
redirect("registrasi/reg");
}
$var['data'] = $this->db->query("select * from t_user where USER_ID= '$id_user'")->row_array();
$var1['data'] = $this->db->query("select * from t_publisher where id_publisher = '$id_publis'")->row_array();
$var2['data'] = $this->db->query("select * from t_label where id_label = '$id_lab'")->row_array();
$this->load->view('update', $var,$var1,$var2);
}
whats wrong with my code? please help. thanks before.
Your UPDATE clause is setting the id_publisher column to NULL, and, based on the name of the column and the error you're receiving, that column is the table's PRIMARY KEY with a setting of unsigned NOT NULL.
Because of this, when you do id_publisher = NULL, MySQL converts it to id_publisher = 0 due to the unsigned part. This will execute fine the first time, however, when you run it on a second row you will now be attempting to insert a second primary-key value of 0, which is not allowed.
Based on the location of the die() statement in your sample code, I'm assuming the following block is the culprit:
$data1 = array(
'id_publisher' => $id_publis,
'publisher' => $publis,
'artis' => $ar,
'id_label' => $id_lab);
$this->db->where('id_publisher', $this->input->post('id'), $data);
$this->db->update("t_publisher",$data1);
Here, your $id_publis variable is either empty or null.
I would suggest to either remove the id_publisher = NULL portion from the UPDATE clause which is as simple as removing 'id_publisher' => $id_publis, from the $data1 array, or rethink the reason you actually need to set it to null to begin with (in this case, would deleting the row be more beneficial?)