Cakephp save data and read MAX - cakephp

I'm trying to save data in CakePHP in this way:
get max entry_id from table translations
(SELECT MAX(entry_id) as res FROM translations) + 1
save data into translations table
$translationData = array('entry_id' => $entry_id, 'language_id' => $key, 'text' => $item);
$translation = new Translation();
$translation->set($translationData);
$translation->save();
again get max entry_id
save next set of data
again get max entry_id
save next set of data
Please have a look at my code:
$this->request->data['Product']['name_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['name']);
$this->request->data['Product']['description_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['description']);
$this->request->data['Product']['seo_title_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_title']);
$this->request->data['Product']['seo_keywords_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_keywords']);
$this->request->data['Product']['seo_desc_tr_id'] = $this->Translation->saveTranslations($this->request->data['Product']['seo_desc']);
saveTranslations method:
public function saveTranslations($data) {
$entry_id = $this->getNextFreeId();
foreach($data as $key => $item) {
if($item != "") {
$this->create();
$temp['Translation']['entry_id'] = $entry_id;
$temp['Translation']['language_id'] = $key;
$temp['Translation']['text'] = $item;
$this->save($temp);
}
}
return $entry_id;
}
getNextFreeId method:
public function getNextFreeId() {
$result = $this->query("SELECT MAX(entry_id) as res FROM translations");
return $result[0][0]['res'] + 1;
}
I don't know why entry_id have all the time the same value.

After many hours of searching for solution I finally managed to solve the problem in very easy way - just add false parameter in query method:
$this->query("INSERT INTO translations(entry_id, language_id, text) VALUES($entry_id, $key, '$item')", false);
and
$result = $this->query("SELECT SQL_CACHE MAX(entry_id) as res FROM translations", false);

Related

foreach by quantity in laravel

I develop a ticketing system which user have to choose the quantity of ticket category. I want to save the record to database by the total of quantity. But it seems to be failed. I end up only save the record by category id. Here is the result when I try to return it.
and this is my code in controller.
public function ticket_checkout(Request $request)
{
$ctg_id = $request->cat_id;
$price = $request->price;
$name = $request->name;
$qty = $request->qty;
// return count($qty);
$data = [];
$i = 0;
foreach($qty as $item){
if($qty[$i] != 0){
$data[] = [
"ctg_id" => $ctg_id[$i],
"price" => $price[$i],
"qty" => $item,
];
}
$i++;
}
return $data;
Ticket_checkout::insert($data);
// return $qty;
return view('ticket.index', compact('data','qty'));
}
I wonder if I missing something here? I tried to do looping 'for' by quantity inside the 'foreach' but it seems not working too.

PUT request with formData could not update using react.js and laravel

I am not receiving formdata in the Api endpoint which is being sent by fetch and PUT method.
I used the POST method and it worked out which i think is not recommended for updating.
I have react running on localhost:3000 and the laravel-API running on localhost:5000.
This is the route in API
Route::put('updateSlide/{id}', 'SlidesController#updateSlide');
This is what is in the controller
public function updateImage(Request $request, int $id)
{
$image = $this->slideRepo->findSlideById($id)->image;
if ($image) {
$result = Storage::disk('ucmp')->delete($image);
}
if ($request->hasFile('image') && $request->file('image') instanceof UploadedFile) {
return $this->slideRepo->saveCover($request->file('image'));
} // return response()->json($data);
// data is an array (note)
return null;
}
public function updateSlide(Request $request, int $id)
{
$imageUrl=$this->updateImage($request, $id);
return response()->json($this->slideRepo->updateSlide([
'caption' => $request['caption'],
'image' => $imageUrl,
'url' => $request['url']
],$id));
}
This is the function sending to fetch
export const updateSlideApi = (token, _slide, id) => {
return {
url: `${BASE_URL}/api/updateSlide/${id}`,
opt: API.requestOptions("PUT",token,null,{ body: _slide }, true)
};
};
In my header i do not have the content-type.
I expect json data from the laravel API function but am having an error, " Can only throw objects"
PHP does not parse the body of a PUT request.
Use POST and add parameter _method with value PUT.
PHP put has given me tough time, use this function will save your time parsing it else method:
function parsePutRequest()
{
// Fetch content and determine boundary
$raw_data = file_get_contents('php://input');
$boundary = substr($raw_data, 0, strpos($raw_data, "\r\n"));
// Fetch each part
$parts = array_slice(explode($boundary, $raw_data), 1);
$data = array();
foreach ($parts as $part) {
// If this is the last part, break
if ($part == "--\r\n") break;
// Separate content from headers
$part = ltrim($part, "\r\n");
list($raw_headers, $body) = explode("\r\n\r\n", $part, 2);
// Parse the headers list
$raw_headers = explode("\r\n", $raw_headers);
$headers = array();
foreach ($raw_headers as $header) {
list($name, $value) = explode(':', $header);
$headers[strtolower($name)] = ltrim($value, ' ');
}
// Parse the Content-Disposition to get the field name, etc.
if (isset($headers['content-disposition'])) {
$filename = null;
preg_match(
'/^(.+); *name="([^"]+)"(; *filename="([^"]+)")?/',
$headers['content-disposition'],
$matches
);
list(, $type, $name) = $matches;
isset($matches[4]) and $filename = $matches[4];
// handle your fields here
switch ($name) {
// this is a file upload
case 'userfile':
file_put_contents($filename, $body);
break;
// default for all other files is to populate $data
default:
$data[$name] = substr($body, 0, strlen($body) - 2);
break;
}
}
}
return $data;
}

CakePHP Custom Query Paginator

Currently I am got 2 page require Pagination.
I also do some research such as setting or at model do the custom Query. However the Paginator can't work.
Now I am trying add custom query paginator to index page. (I need to use group by)
I also trying to add custom query paginator to view page. ( I need base on the id)
Controller:
public function index() {
$setting = $this->Paginator->settings = $this->Report->query('
SELECT SUM( seats_occupied ) as totalOccupied, event_date, r.event_date_id
FROM reports r, event_dates ed WHERE r.event_date_id = ed.event_date_id
GROUP BY event_date
');
debug($this->Paginator->paginate());
$this->set('showDate',$setting);
}
public function view($eventDateId = null){
if (!$eventDateId) {
throw new NotFoundException(__('Invalid post'));
}
// We only want single post so we use FindById.
$post = $this->Report->findAllByEventDateId($eventDateId);
// debug($this->Paginator->paginate($post));
if (!$post) {
//if user requet fypcakephp/view without id will throw the not found except
throw new NotFoundException(__('Invalid post'));
}
$setting = $this->Paginator->settings = $this->Report->query("
SELECT *
FROM reports where event_date_id='$eventDateId' order by period asc
");
//array( 'conditions' => array( 'event_date_id' => $post));
debug($setting);
$this->set('viewData', $setting); //Then send this data
}
I also got try do at model custom Query however If I do this way , my view can't get the data I want due to I using "Group By".
//To custom the paginate display the thing you want. (This one return)
//public function paginate($conditions, $fields, $order, $limit, $page = 1,
// $recursive = null, $extra = array())
//{
// $recursive = 0;
//
// // Mandatory to have
// $this->useTable = false;
// $sql = '';
//
//
// $sql .= " select * from reports;";
//
//
//
// $sql .= " SELECT SUM( seats_occupied ) as totalOccupied, event_date,r.event_date_id
// FROM reports r, event_dates ed WHERE r.event_date_id = ed.event_date_id
// GROUP BY event_date; ";
//
//
//
// // Adding LIMIT Clause
//// $sql .= (($page - 1) * $limit) . ', ' . $limit;
//
// $results = $this->query($sql);
//
// return $results;
//}
//public function paginateCount($conditions = null, $recursive = 0, $extra = array())
//{
// $sql = '';
//
// $sql .= "SELECT SUM( seats_occupied ) as totalOccupied, event_date ,r.event_date_id
// FROM reports r, event_dates ed WHERE r.event_date_id = ed.event_date_id
// GROUP BY event_date";
//
// $this->recursive = $recursive;
//
// $results = $this->query($sql);
//
// return count($results);
//}

Which of Database::<QUERY_TYPE> I should use in Kohana 3.3?

I need perform query "LOCK TABLE myTable WRITE"
<?php
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(Database::WHAT_IS_THE_TYPE_SHOULD_SPECIFY_HERE_?, $query);
In framework Kohana 3.3
file ~/modules/database/classes/Kohana/Database.php
implements folowing types:
const SELECT = 1;
const INSERT = 2;
const UPDATE = 3;
const DELETE = 4;
but none of them fit in my case.
Any idea. Thanks.
Google works wonders. http://forum.kohanaframework.org/discussion/6401/lockunlock/p1
You can pass NULL as the first argument:
$db = Database::instance();
$query = 'LOCK TABLE `myTable` WRITE';
$db->query(NULL, $query);
From Kohana: http://kohanaframework.org/3.3/guide-api/Database_MySQL#query
if ($type === Database::SELECT)
{
// Return an iterator of results
return new Database_MySQL_Result($result, $sql, $as_object, $params);
}
elseif ($type === Database::INSERT)
{
// Return a list of insert id and rows created
return array(
mysql_insert_id($this->_connection),
mysql_affected_rows($this->_connection),
);
}
else
{
// Return the number of rows affected
return mysql_affected_rows($this->_connection);
}
As you can see that's why you're able to pass NULL.

How do I use fixed fields in CakeDC's csvUpload behavior in Util plugin

I am using the csvUpload behavior of the Utils plugin by CakeDC, on a CakePHP 2.2.1 install.
I have it working great it's processing a rather large csv successfully. However there are two fields in my table / Model that would be considered fixed, as they are based on ID's from from associated models that are not consistent. So I need to get these fixed values via variables which is easy enough.
So my question is, how do I use the fixed fields aspect of csvUpload? I have tried that following and many little variation, which obviously didn't work.
public function upload_csv($Id = null) {
$unique_add = 69;
if ( $this->request->is('POST') ) {
$records_count = $this->Model->find( 'count' );
try {
$fixed = array('Model' => array('random_id' => $Id, 'unique_add' => $unique_add));
$this->Model->importCSV($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
} catch (Exception $e) {
$import_errors = $this->Model->getImportErrors();
$this->set( 'import_errors', $import_errors );
$this->Session->setFlash( __('Error Importing') . ' ' . $this->request->data['Model']['CsvFile']['name'] . ', ' . __('column name mismatch.') );
$this->redirect( array('action'=>'import') );
}
$new_records_count = $this->Model->find( 'count' ) - $records_count;
$this->Session->setFlash(__('Successfully imported') . ' ' . $new_records_count . ' records from ' . $this->request->data['Model']['CsvFile']['name'] );
$this->redirect(array('plugin'=>'usermgmt', 'controller'=>'users', 'action'=>'dashboard'));
}
}
Any help would be greatly appreciated as I have only found 1 post concerning this behavior when I searching...
I made my custom method to achieve the same task. Define the following method in app\Plugin\Utils\Model\Behavior
public function getCSVData(Model &$Model, $file, $fixed = array())
{
$settings = array(
'delimiter' => ',',
'enclosure' => '"',
'hasHeader' => true
);
$this->setup($Model, $settings);
$handle = new SplFileObject($file, 'rb');
$header = $this->_getHeader($Model, $handle);
$db = $Model->getDataSource();
$db->begin($Model);
$saved = array();
$data = array();
$i = 0;
while (($row = $this->_getCSVLine($Model, $handle)) !== false)
{
foreach ($header as $k => $col)
{
// get the data field from Model.field
$col = str_replace('.', '-', trim($col));
if (strpos($col, '.') !== false)
{
list($model,$field) = explode('.', $col);
$data[$i][$model][$field] = (isset($row[$k])) ? $row[$k] : '';
}
else
{
$col = str_replace(' ','_', $col);
$data[$i][$Model->alias][$col] = (isset($row[$k])) ? $row[$k] : '';
}
}
$is_valid_row = false;
foreach($data[$i][$Model->alias] as $col => $value )
{
if(!empty($data[$i][$Model->alias][$col]))
{
$is_valid_row = true;
}
}
if($is_valid_row == true)
{
$i++;
$data = Set::merge($data, $fixed);
}
else
{
unset($data[$i]);
}
}
return $data;
}
And you can use it using:
$csv_data = $this->Model->getCSVData($this->request->data['Model']['CsvFile']['tmp_name'], $fixed);
Here $csv_data will contain an array of all of those records from the csv file which are not empty and with the fixed field in each record index.
So as I was telling Arun, I answered my own question and figured it out. I was looking to broad instead of really examining what was in front of me. I started running some debugging and figured it out.
First of all, $unique_add = 69 is seen as an int, duh. In order for it to be added to the csv it need to viewed as a string. So it simply becomes, $unique_add = '69'.
I couldn't enter the value of $Id directly into the fixed array. So I just had to perform a simple find to get the value I needed.
$needed_id = $this->Model->find('first', array(
'condition'=>array('Model.id'=>$Id)
)
);
$random_id = $needed_id['Model']['id'];
Hopefully this won't be needed to help anyone because hopefully no one else will make this silly mistake. But one plus... Now there's actually more than one post on the internet documenting the use of fixed fields in the CakeDC Utils plugin.

Resources