How to insert on first time and update for the second time - mysql

I want to insert the row if it's a first entry of the day else I want to update the row..How can I do that..Currently I had done for update and don't know how to do it for insert..Please help me to achieve this..
This is my controller code:
$startdate = $this->input->post('TDate');
$date = str_replace('/', '-', $startdate);
$newDate = date("Y-m-d", strtotime($date));
$data1 = array(
'tdate'=>$newDate,
'total_credit'=>$total_credit['amount'],
'total_debit'=>$total_debit['amount'],
);
$this->db->where('tdate',$newDate);
$this->db->update('daytot',$data1);

Try below one
$newDate = date("Y-m-d", strtotime($this->input->post('TDate')));
$data1 = array(
'tdate' => $newDate,
'total_credit' => $total_credit['amount'],
'total_debit' => $total_debit['amount'],
);
//Check record is exist for the request date
$objQuery = $this->db->get_where('daytot', array('tdate' => $newDate));
if ($objQuery->num_rows() > 0) { //UPDATE
$this->db->where('tdate', $newDate);
$this->db->update('daytot', $data1);
}
else { //INSERT
$this->db->insert('daytot', $data1);
}
Hope this will work :)

One solution to your problem, which you may find acceptable, would be to just always insert your transactional data as it comes along. That is, the first record and every subsequent record would come into the database as a separate insert. Then, if you needed to do any reporting, e.g. by hour or day, you could simply hit the table of transactions and aggregate.
The problem you are trying to solve, namely conditionally doing an insert at the start of a day, is troublesome, because in addition to what you already pointed out, you might also have to worry about multi nodes in your application trying to do this at the same time.

Related

Loop in column name MYSQL

I am using MYSQL.My table contains column name as Revenue2000,Revenue2001,Revenue2002,....,Revenue 2016,Revenue 2017
Traditional way(to select all column manually):
select Revenue2005,
Revenue2006,
Revenue2007,
Revenue2008,
Revenue2009,
Revenue2010
from table_name
Desired Way:
I want to write a Dynamic select statement .There should 2 variables "start" and "end" so that i can make it dynamic.User has the option to specify the starting year and ending year and can view the desired result.
In above case, Start year =2005
End Year=2010
Yes, it's bad database design, and the best answer would be "don't do this at all, just fix your table." Unfortunately, sometimes you're stuck with something someone else made, and can't change it for whatever reason, but you still need to accomplish something (welcome to my life). I would do it like this:
Get the years from user input and convert them to integers in case someone enters something silly/naughty. Don't depend on client-side validation. Prepared statements won't help you here because these will be used as parts of column names.
$start = (int) $_POST['start'];
$end = (int) $_POST['end'];
Do a quick sanity check to make sure that the range makes sense and should work with what's in your database.
if ($start > $end
|| $start < $lowest_year_in_your_db
|| $end > $highest_year_in_your_db) {
// quit with error
}
Then you can generate a list of columns to use in your query. Here's one way with range and array_map, but you could also just build a string with a for loop.
$columns = implode(', ', array_map(function($year) {
return "Revenue$year";
}, range($start, $end)));
$sql = "SELECT $columns FROM table_name";
Theoretically, the worst thing that should be able to happen with this is that you'd get a column that didn't exist, and your query would fail.
But really, if you have any choice about it, don't do this. Normalize your database as people have stated in the comments, or find whoever keeps adding more year columns to the database and make them do it.
As already pointed out the database design is horrible. You should really normalize it, it's worth the effort.
However if that is not possible at the moment the follow code should do exactly what you need:
// Connect to DB
$mysqli = new mysqli("localhost", "USERNAME", "PASSWORD", "DATABASE");
// Get column names
$columns = $mysqli->query('SHOW COLUMNS FROM revenue')->fetch_all();
$columnNames = array_column($columns, 0);
// Extract years from column names
$years = array_map(function($columnName) {
return (int) substr($columnName, -4);
}, $columnNames);
// Get max and min year
$maxYear = max($years);
$minYear = min($years);
// Input year start and end
$start = (int) $_POST['start']; // User-input
$end = (int) $_POST['end']; // User-input
// Avoid wrong inputs
if($start > $end || $start < $minYear || $end > $maxYear) {
die('Error');
}
// Create the SQL-query
$selectColumns = [];
for ($i = $start; $i <= $end; $i++) {
$selectColumns[] = "revenue" . $i;
}
$queryString = "SELECT " . implode(", ", $selectColumns) . " FROM TABLE";
// Run the query
// ...

How to get last inserted id with insert method in laravel

In my laravel project I am inserting multiple records at time with modelname::insert method. Now I want to get last inserted id of it.I read somewhere when you insert multiple records with single insert method and try to get the last_record_id it will gives you the first id of the last inserted query bunch. But my first question is how to get last record id with following code .If I am able to get first id of the bunch .I ll make other ids for other record by my own using incremental variable.
Code to insert multiple record
if(!empty($req->contract_name) && count($req->contract_name)>0)
{
for($i=0; $i<count($req->contract_name); $i++)
{
$contract_arr[$i]['client_id'] = $this->id;
$contract_arr[$i]['contract_name'] = $req->contract_name[$i];
$contract_arr[$i]['contract_code'] = $req->contract_code[$i];
$contract_arr[$i]['contract_type'] = $req->contract_type[$i];
$contract_arr[$i]['contract_ext_period'] = $req->contract_ext_period[$i];
$contract_arr[$i]['contract_email'] = $req->contract_email[$i];
$contract_arr[$i]['created_at'] = \Carbon\Carbon::now();
$contract_arr[$i]['updated_at'] = \Carbon\Carbon::now();
$contract_arr[$i]['created_by'] = Auth::user()->id;
$contract_arr[$i]['updated_by'] = Auth::user()->id;
if($req->startdate[$i] != ''){
$contract_arr[$i]['startdate'] = date('Y-m-d',strtotime($req->startdate[$i]));
}
if($req->enddate[$i] != ''){
$contract_arr[$i]['enddate'] = date('Y-m-d',strtotime($req->enddate[$i]));
}
}
if(!empty($contract_arr)){
Contract::insert($contract_arr);
}
}
You should be able to call it like this
$lastId = Contract::insert($contract_arr)->lastInsertId();
If i see right, you're using a Model. Direct inserting only shows an success boolean. Try this instead:
Contract::create($contract_arr)->getKey()

Code Igniter - not showing the entry I need

I have the following code to get one line for each MAC with the LATEST state. The problem I have is that I get one line but not with the latest state but rather with the earliest.
function get_active_devices($min_duration, $max_duration)
{
//get all active devices DESC order
$this->db->distinct();
$this->db->group_by('mac');
$this->db->order_by("id", "desc");
$this->db->select('data.mac, state, time, iot_bo.notified, iot_bo.op_state, iot_bo.Name');
$this->db->where('time >', time()-$max_duration);
$this->db->where('time <', time()-$min_duration);
$this->db->join('iot_bo', 'iot_bo.mac = data.mac');
$this->db->where('iot_bo.op_state', '1');
$query = $this->db->get();
return $query;
}
Have you tried the query without the distinct and groupBy first? May be the result you want isn't in the total result set to begin with. Because there doesn't seem to be anything wrong with your use of db methods as it is.

Show missing dates inside loop even if they don't exist inside MYSQL

I have following mysql query
SELECT count(order_id), date FROM tbl_order WHERE campaign_status = 'In Progress' or campaign_status = 'Pending' GROUP BY DATE_FORMAT(date,'%d %b %y')
and then following loop
<?php do { ?>
['<?php echo $row_chartData['date']; ?>', <?php echo $row_chartData['count(order_id)']; ?>],
<?php } while ($row_chartData = mysql_fetch_assoc($chartData)) ?>
this loop is used to create data for my chart. Now the problem is that there are certain days that users dont make orders in my store so those dates are not stored inside database, so when I loop trough those dates are not showed in above results and inside the chart.
The question I have, is there any way to show those missing dates in loop above even if they dont exist inside mysql database.
Thanks for help.
Well, in this case, create a temporary array based on the date range, e.g. if you want to show the graph from May 1, to May 31.
Loop from 1 to 30,
set $data[i] = 0;
Now loop through the db records and set
$data['date'] = $row['count']
Yes.
Firstly make $row_chartData as array instead of a mysql_result.
1) find the min date in the range or whichever date you want to start with
function _getDate($row) {
return $row['date'];
}
$dates = array_map('_getDate', $row_chartData);
$minDate = min($dates);
2) find the max date in the range or whichever date you want to end with
$maxDate = min($dates);
$dateRangeArray = array();
$date = $minDate;
while($date < $maxDate) {
$dateRangeArray[] = $date;
$date = date('Y-m-d', strtotime($date . ' +1 day'));
}
3) make the key of each element in your $row_chartdata array be the value of the date index
foreach($row_chartData as $key => $row) {
$row_chartData[$row['date']] = $row;
unset($row_chartData[$key]);
}
4) iterate over each of the days in the range and match that date to the index in your $row_chartdata array
foreach($dateRangeArray as $date) {
if(isset($row_chartData[$date])) {
//do whatever
}
}

Multidimensional Array insert into Mysql rows

I have an Array (twodimensional) and i insert it into my database.
My Code:
$yourArr = $_POST;
$action = $yourArr['action'];
$mysql = $yourArr['mysql'];
$total = $yourArr['total'];
unset( $yourArr['action'] , $yourArr['mysql'] , $yourArr['total'] );
foreach ($yourArr as $k => $v) {
list($type,$num) = explode('_item_',$k);
$items[$num][$type] = $v;
$pnr= $items[$num][pnr];
$pkt= $items[$num][pkt];
$desc= $items[$num][desc];
$qty= $items[$num][qty];
$price= $items[$num][price];
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
I get 5 inserts in the Database but only the 5th have the informations i want. The firsts are incomplete.
Can someone help me?
Sorry for my english.
check if You have sent vars from browser in array (like
input name="some_name[]" ...
also You can check, what You get at any time by putting var_dump($your_var) in any place in script.
good luck:)
You probably want to have your query and the 5 assignments above that outside of the foreach. Instead in a new loop which only executes once for every item instead of 5 times. Your indentation even suggests the same however your brackets do not.
Currently it is only assigning one value each time and executing a new query. After 5 times all the variables are assigned and the last inserted row finally has everything proper.
error_reporting(E_ALL);
$items = array();
foreach($yourArr as $k => $v) {
// check here if the variable is one you need
list($type, $num) = explode('_item_', $k);
$items[$num][$type] = $v;
}
foreach($items as $item) {
$pnr = mysql_real_escape_string($item['pnr']);
$pkt = mysql_real_escape_string($item['pkt']);
$desc = mysql_real_escape_string($item['desc']);
$qty = mysql_real_escape_string($item['qty']);
$price = mysql_real_escape_string($item['price']);
$eintragen = mysql_query("INSERT INTO rechnungspositionen (artikelnummer, menge, artikel, beschreibung,preis) VALUES ('$pnr', '$qty', '$pkt', '$desc', '$price')");
}
Switching on your error level to E_ALL would have hinted in such a direction, among else:
unquoted array-keys: if a constant of
the same name exists your script will
be unpredictable.
unescaped variables: malformed values
or even just containing a quote which
needs to be there will fail your
query or worse.
naïve exploding: not each $_POST-key
variable will contain the string
item and your list will fail, including subsequent use of $num