Hw can I get last inserted id in cakephp 3.x? - php

I am trying to get last inserted id in cake php 3.
if($this->request->is('post')){
$this->loadModel('MyPlaylists');
$playlistData = [];
$playlistData["user_id"] = $_POST['user_id'];
$playlistData["play_list_name"] = $_POST['play_list_name'];
$playlistData["section"] = $_POST['section'];
$playlistData["created"] = date('Y-m-d H:i:s', strtotime('now'));
$playlistData["status"] = 'active';
$playlist_en = $this->MyPlaylists->newEntity();
$this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$this->MyPlaylists->save($playlist_en);
$id=$this->MyPlaylists->id;
}
I have also tried:
$id=$this->MyPlaylists->lastInsertedId;
But it is giving error as below screenshot:

Your code needs some fine tuning.
$playlist_en = $this->MyPlaylists->newEntity();
$playlist_en = $this->MyPlaylists->patchEntity($playlist_en, $playlistData);
$isValid = $this->MyPlaylists->save($playlist_en);
if ($isValid) {
$id = $playlist_en->id;
debug($id); // Check your last insert id
} else {
pr($playlist_en->errors()); // Check errors
}

Make a query selecting the first element of the query ordered in DESC. way
$newPlaylist = $this->Playlists->find('all',['order' => ['Playlists.id' => 'DESC']])->select(['id']);

Related

How to save query in multidimesional array?

I have this script executing as a cron job everyday to update days remaining to pay invoices. I first query every row of my table and attempt to store the data in a multidimensional array but this seems to be storing everything I query in the first element of my array.
Here's my script:
<?php
include '../inc/dbinfo.inc';
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");
error_log( "################################################# UpdateVendorInvoiceDays.php #################################################" );
$three = 3;
$fetchAllInvoices = "SELECT VENDORINVOICEID, VdrInvoiceReceived, PaymentDue, COUNT(*), DATEDIFF(PaymentDue, NOW()) FROM tblVendorInvoices WHERE VdrInvoiceStatusID != ?";
$getInvoices = $conn->prepare($fetchAllInvoices);
$getInvoices->bind_param("i", $three);
$getInvoices->execute();
$result = $getInvoices->get_result();
$rows = array();
$j = 0;
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]); //Only outputs one row
//UPDATE DAYS REMAINING IN EACH ENTRY THAT ISNT PAID
$updateDaysRemaining = "UPDATE tblVendorInvoices SET DaysRemaining = ? WHERE VENDORINVOICEID = ? AND VdrInvoiceStatusID ! = ?";
$setDays = $conn->prepare($updateDaysRemaining);
$k = 0; //incrementor
$numberOfEntries = $rows['COUNT(*)'];
for($k;$k<$numberOfEntries;$k++){
$setDays->bind_param("iii", $rows[$k]["DATEDIFF(PaymentDue, NOW())"],
$rows[$k]['VENDORINVOICEID'], $three);
if($setDays->execute()){
error_log('Cron success');
}else{
error_log('Cron fail');
}
}
?>
Currently the output from my first query is:
[[{"VENDORINVOICEID":88,"VdrInvoiceReceived":"2018-08-21","PaymentDue":"2018-07-27","COUNT(*)":2,"DATEDIFF(PaymentDue, NOW())":-25}]]
and my error log only gives me a notice for $rows['COUNT(*)'] being undefined (which makes sense)
I've looked at other answers here but they don't seem to have the same structure as I do.
EDIT: I also have 2 rows in my database but this only puts out one. I forgot to mention this.
There are a couple of simplifications to get all of the rows. Instead of...
while($row = $result->fetch_assoc())
{
$rows[$j][] = $row;
$j++;
}
echo json_encode($rows[0][0]);
You can just return all rows using fetch_all()...
$rows = $result->fetch_all (MYSQLI_ASSOC);
echo json_encode($rows);
Then encode the whole array and not just the one element - which is what $rows[0][0] was showing you.
As for you other problem - change in your select statement to
COUNT(*) as rowCount
and then you can use this alias for the field reference...
$rows['COUNT(*)']
becomes
$rows['rowCount']

PHP Array to string to mysql - empty record

I am on point where I have to usk on forum.
So, I have an array that is my return from join table sql query.
i am displaying it correctly without the problem.
but some of those values I want to put in different table of mysql database.
$array = joint_table();
$array_value = array['key'];
I can echo array_value and it's displaying correctly, also checked variable type and it returns STRING.
however when I am inserting it into the table, it's empty cell.
I am inserting other stuff like date() and such and that is inserted correctly.
So my sql query works fine, besides I am using same query in other places without problem.
Only values I have from that array are not inserting, but still can echo them.
<?php
$page_title = 'Complete Task';
require_once('includes/load.php');
// Checkin What level user has permission to view this page
page_require_level(2);
$task = join_task_table((int)$_GET['id']);
?>
<?php
if(isset($_POST['complete_task'])){
$area = $task['area'] ;
$jig = $task['jig'];
$desc = $task['description'];
$freq = $task['freq'];
$date = make_date();
$user = current_user();
$user_done = remove_junk(ucfirst($user['name']));
$comment = remove_junk($db->escape($_POST['comment']));
if(empty($errors)){
$sql = "INSERT INTO tpm_history (area_name,jig_name,description,frequency,date_done,done_by_user,comment)";
$sql .= " VALUES ('{$area}','{$jig}','{$desc}','{$freq}','{$date}','{$user_done}','{$comment}')";
$result = $db->query($sql);
if($result && $db->affected_rows() === 1){
$session->msg('s',"Job Completed");
redirect('home.php', false);
} else {
$session->msg('d',' Sorry failed to complete the task!');
redirect('task_complete.php?id='.$task['id'], false);
}
} else{
$session->msg("d", $errors);
redirect('task_complete.php?id='.$task['id'],false);
}
}
?>
I am lost. Help.

When two or three user request the same time then I have duplicate ID

I get the last ID and increment it and store it as second ID of my invoice when two or three user request at the same time it store duplicated ID in DB. HERE IS THE CODE
$id_num = DB::table('slips')->latest('id')->first();
$now = \jDate::forge('now')->format('date');
$old = $id_num->date;
$slep_id = 0;
if($now>$old){
$slep_id = 1;
}
else{
$slep_id = $id_num->id_num+1;
}
$formatted_slep = sprintf("%04d",$slep_id);
Now when I store it in the DB it some times it duplicate
$slip = new Slip;
$slip->id = $formatted_slep;
$slip->save();
Use transaction :
DB::transaction(function () {
$slip = new Slip;
$slip->id = $formatted_slep;
$slip->save();
});

Updating a row number which has been randomised

So I currently have a random number being generated in PHP and I want to know how I go about updating the row number in my selected table. Code below:
$sxiq = mysql_query("SELECT * FROM `starting_eleven` WHERE `team_id`=$uid");
$sxir = mysql_fetch_row($sxiq);
$first = rand(1,11);
$stat_changed = rand(11,31);
$up_or_down = rand(1,2);
if ($up_or_down == 1) {
$player_name = explode(" ", $sxir[$first]);
$fn = $player_name[0];
$ln = $player_name[1];
$statq = mysql_query("SELECT * FROM `players` WHERE `first_name`=$fn AND `last_name`=$ln AND `user_id`=".$_SESSION['user_id']);
$statr = mysql_fetch_row($statq);
$stat = $statr[0];
}
I would like to update the row $stat_changed from the database, but I'm not sure if this is possible without doing a long if statement, telling the code if $stat_changed = 13 $stat = pace or something along those lines, but if this is the way it must be done then I'll have to. Just thought I'd see if there was any other simpler ways of doing this.
Thanks in advance
if ($stat_changed == 13) {
//insert UPDATE statement here
}

Zend Date giving me zeroes, why?

More problems with dates.
Basically I'm trying to populate a table with some datetime values from Zend. The datatype of the column that I'm trying to populate is 'datetime'. However, no matter which constant I try the column is always populated with zeroes. I've tried Zend_Date::ISO_8601, Zend_Date::DATETIME, Zend_Date::now() to no avail. Pleas help.
Here's the code:
if(!$exists){
$date_time = Zend_Date::DATETIME;
/*
* Create the new site record
*/
$site_row = $site_table->createRow();
//if(isset($n_r['id'])) $row->id = $n_r['id'];
$site_row->name = $n_r['name'];
$site_row->active = 1;
$site_id = $site_table->total() + 1;
$address_id = $address_table->total() + 1;
$site_row->id = $site_id;
$site_row->address_id = $address_id;
/*
* Create the address record to go with it
*/
$address_row = $address_table->createRow();
$address_row->postcode = $n_r['postcode'];
$address_row->address_line1 = $n_r['name'];
$address_row->start_date = $date_time;
$address_row->id = $address_id;
$address_row->save();
$array[] = $site_row->toArray();
$site_row->save();
/*
* Create the new site2address record to go with it
*/
$site2address_row = $site2address_table->createRow();
$site2address_row->site_id = $site_id;
$site2address_row->address_id = $address_id;
$site2address_row->start_date = $date_time;
}else{
$array[] = $exists;
}
mySQL expects input for DATETIME columns to be
YYYY-MM-DD HH:MM:SS
independent from the locale you are using. I can't see a Zend constant for that, you may need to format it yourself.
you can use mysql function like NOW() for more convenience way. if you are at mysql code bellow may work for you.
$address_row->start_date = new Zend_Db_Expr('NOW()');

Categories