I have some functions which are used to insert and update database tables in my Symfony2 project. For those functions I want to generate a verbose SQL log for all insert and update queries which are being executed with their result.
I have tried to do it manually but I am unable to get the SQL queries from the object that is persist and Flushed.
Here is my controller function:
private function pushChapterToCdpCodes($testObjectEntity, $testReleaseId) {
$chapterTitle = $testObjectEntity->getTitle();
$chapterNumber = $testObjectEntity->getNumber();
$chapterOriginalId = $testObjectEntity->getOriginalId();
// update chapter table
if ($chapterOriginalId) {
$chapter = $this->chapterRepository->findOneBy(array('id' => $chapterOriginalId));
} else {
$bookTitle = $testObjectEntity->getBook()->getTitle();
$bookObject = $this->bookRepository->findOneBy(array('title' => $bookTitle));
$bookId = $bookObject->getId();
$bookPart = $testObjectEntity->getBookPart();
$chapter = new \ICC\BookBundle\Entity\Chapter();
if ($bookPart) {
$bookPartOriginalNumber = $testObjectEntity->getBookPart()->getNumber();
$bookPartOriginalTitle = $testObjectEntity->getBookPart()->getTitle();
$originalBookPart = $this->bookPartRepository->findOneBy(array('number' => $bookPartOriginalNumber, 'title' => $bookPartOriginalTitle));
$chapter->setBookPart($originalBookPart);
} else {
$chapter->setBook($this->bookRepository->findOneBy(array('id' => $bookId)));
}
}
$chapter->setTitle($chapterTitle);
$chapter->setNumber($chapterNumber);
$chapter->setErrataReleaseId($testReleaseId);
$this->cdpCodesEm->persist($chapter);
$this->cdpCodesEm->flush();
}
I need the SQL log for the above $this->cdpCodesEm->persist($chapter); result.
Please help me what is the right way to do this.
Related
I have a website in PHP and a log in page. which is loaded when the class is construct if the session "Caisse_login" is not created. I have seen a bug which i have fixed with exit(), but I wanted to know if there is any other way of doing it.
here is the beginning of my class:
class caisses extends controller{
public function __Construct(){
$this->caisseModel = $this->model('caisse');
if(!isset($_SESSION['Caisse_login']) OR $_SESSION['Caisse_login']==FALSE){
$this->login();
exit();
}
}
everytime an url is entered it will call the associated method. so if i use the following URL:
caisselive/en/caisses/showTable/3
it will therefore create the class above caisses, and the following method:
public function showTable($tableId = 0){
// control if there is at least one table
if(!$this->caisseModel->countTable()){
flash('Transaction', 'No any table have been created', 'alert alert-warning');
redirect('caisses/transaction');
}else if($tableId==0){
$data = [
'table' => $this->caisseModel->getAllTable(),
];
$this->view('caisses/tableShow', $data);
}else{
// control if the ID provided is an existing table
if(!$this->caisseModel->getTempTablebyID($tableId)){
flash('Transaction', 'The table does not exist', 'alert alert-warning');
redirect('caisses/showTable');
}else{
//Display the table
$totalPrice = 0;
$productsQuery = $this->caisseModel->getTempTableProducts($tableId);
$tempTable = $this->caisseModel->getTempTablebyID($tableId);
$i=0;
$k=0;
$totalPricePaid=0;
$productsPaid = null;
foreach($productsQuery as $products_1){
// control if it has already been paid
if($products_1->paid==0){
for($j=0;$j<$products_1->qty;$j++){
$products[$i]['productName'] = $products_1->product_name;
$products[$i]['productID'] = $products_1->id_product;
$products[$i]['transactionId'] = $products_1->id;
$products[$i]['rebate'] = $products_1->percentage;
$products[$i]['rebateID'] = $products_1->id_rebate;
$products[$i]['rebateName'] = $products_1->name;
$products[$i]['qty'] = 1;
$products[$i]['price'] = $products_1->price_s;
$products[$i]['priceTotInt'] = number_format($products_1->price_s * 1 * (1-($products_1->percentage/100)), 2);
$totalPrice = $totalPrice + $products[$i]['priceTotInt'] ;
$i++;
}
//create the list of what it has already have been paid
}else{
$productsPaid[$k]['productName'] = $products_1->product_name;
$productsPaid[$k]['productID'] = $products_1->id_product;
$productsPaid[$k]['transactionId'] = $products_1->id;
$productsPaid[$k]['rebate'] = $products_1->percentage;
$productsPaid[$k]['rebateID'] = $products_1->id_rebate;
$productsPaid[$k]['rebateName'] = $products_1->name;
$productsPaid[$k]['qty'] = $products_1->qty;
$productsPaid[$k]['price'] = $products_1->price_s;
$productsPaid[$k]['priceTotInt'] = number_format($products_1->price_s * $products_1->qty * (1-($products_1->percentage/100)), 2);
$totalPricePaid = $totalPricePaid + $productsPaid[$k]['priceTotInt'] ;
$k++;
}
}
$data = [
'products' => $products,
'productsPaid' => $productsPaid,
'dateTable' => $tempTable->date,
'nameTable' => $tempTable->nameTable,
'tableId' => $tableId,
'rebate' => $this->caisseModel->getAllRebate(),
'totalPrice' => number_format($totalPrice, 2),
'totalPricePaid' => number_format($totalPricePaid, 2)
];
$this->view('caisses/tableShowDetail', $data);
}
}
}
what happens if the person is not loged in, it will load the 2 views, as explained I have kinda fixed it with the exit() when the class is constructed, but I am wondering if there is not a better way of doing it ?
There are different options. If you use a framework, you could use a method to redirect this request to another controller. Another option is to set a boolean to indicate that this user is not logged in and you process this parameter in your controller.
The easiest solution you have already implemented, just an exit, but this could cause some issues if you need to execute something on the end of every operation in a controller.
It's been a while since I've used Laravel and I'm pulling my hair out over the below issue, seems to be relatively straight forward and probably 100% obvious.
I'm adding some new fields to an existing view, I've created a new model, added the relations and added the fields. I can confirm that I'm able to view the data on the View successfully, I can take the data from the view successfully and insert a new record on the target table.
The problem I'm having is I'm unable to update an existing record, I can retrieve the record by ID, but I can't use the object selector ($object->data) on it, I've added the function and the comments below:
//Create the license
$license = License::where('id', $venue->license_id)->get();
if(empty($license->id))
{
Log::notice("Nothing to show");
} else {
//I have added this in as a sanity check, I've been able to
//perform Log::notice($license); successfully but the below doesn't work?
Log::notice($license->id);
Log::notice($license->license_name);
}
//This works, I am able to create a new License if there is no ID set.
$license_class_id = $request->get('license_class_id');
$license_type_id = $request->get('license_type_id');
$liquor_license_no = $request->get('liquor_license_no');
$site_reference_no = $request->get('site_reference_no');
$holder_name = $request->get('holder_name');
$license_name = $request->get('license_name');
$trading_name = $request->get('trading_name');
//This works
if( !$license || !$license->exists ) {
$license = new License;
}
//This is to update the object but it doesn't seem to happen.
$license->license_class_id = $license_class_id;
$license->license_type_id = $license_type_id;
$license->liquor_license_no = $liquor_license_no;
$license->site_reference_no = $site_reference_no;
$license->holder_name = $holder_name;
$license->license_name = $license_name;
$license->trading_name = $trading_name;
if ( ! $license->save() ) {
return $license->errors();
}
if(!empty($license->id))
{
$venue->license_id = $license->id;
}
if ( ! $venue->save() ) {
return $venue->errors();
}
use update() method for update not save(). save() is used at the insert time
$license->update();
And fetch record as single collection. If id is not primary key then by below way
//Create the license
$license = License::where('id', $venue->license_id)->first();
And if id is primary key then you directly get by
$license = License::find($venue->license_id);
You can use updateOrCreate method here too.
By this code,
//Create the license
$license = License::where('id', $venue->license_id)->first();
if(empty($license))
{
Log::notice("Nothing to show");
} else {
//I have added this in as a sanity check, I've been able to
//perform Log::notice($license); successfully but the below doesn't work?
Log::notice($license->id);
Log::notice($license->license_name);
}
//This works, I am able to create a new License if there is no ID set.
$license_class_id = $request->get('license_class_id');
$license_type_id = $request->get('license_type_id');
$liquor_license_no = $request->get('liquor_license_no');
$site_reference_no = $request->get('site_reference_no');
$holder_name = $request->get('holder_name');
$license_name = $request->get('license_name');
$trading_name = $request->get('trading_name');
License::updateOrCreate([
'license_class_id' => $license_class_id ,
'license_type_id' => $license_type_id,
'license_type_id' => $license_type_id,
'license_type_id' => $license_type_id,
'holder_name' => $holder_name,
'license_name' => $license_name,
'trading_name' => $trading_name
]);
For more information check this link.
If you will use this method, You do not need to check if a record exists or not. That is the advantage.
I have a code block where multiple table database operation are done. I need to keep this code block in transaction. I am trying in following way in cakephp 3.
$saveStatus = 1;
$conn = ConnectionManager::get('default');
$conn->begin();
$tableArticles = TableRegistry::get('Articles');
$tableUsers = TableRegistry::get('Users');
$articlesEntity = $tableArticles->newEntities($categoriesArray);
foreach ($articlesEntity as $entity) {
if(!$tableArticles->save($entity))
{
$saveStatus = 0;
}
}
$usersEntity = $tableUsers->newEntities($usersArray);
foreach ($usersEntity as $entity) {
if(!$tableUsers->save($entity))
{
$saveStatus = 0;
}
}
if($saveStatus ==1)
{
$conn->commit();
}
else
{
$conn->rollback();
}
But the transaction works for only one table.I want multiple table operation should be in transaction.
In cake 2, we do transaction using begin() and commit() on each model data source like following.
$mealOptionDataSource = $this->MealOptionFood->getDataSource ();
$foodExtrasDataSource = $this->FoodExtras->getDataSource ();
$complexOptionDataSource = $this->ComplexOptionFood->getDataSource ();
$mealOptionDataSource->begin ();
$foodExtrasDataSource->begin ();
--- Code here---
$mealOptionDataSource->commit ();
$foodExtrasDataSource->commit ();
$complexOptionDataSource->commit ();
I can't find a way how to do it in cake 3.
Thank in advances.
Try this:
http://api.cakephp.org/3.1/class-Cake.Database.Connection.html#_transactional
$connection->transactional(function ($connection) {
$connection->newQuery()->delete('users')->execute();
});
In the transactional function, the 'commit' or 'rollback' occurs automatically depending on the result of all queries inside.
i am writing a program using mvc , and because the program i am writing is for admitting bank transactions, the resaults this program gives me is very important to me. and i need this to work without any logical errors and everything should workout with needed focus and giving me the exact thing i expect it to give. the thing that i want it to do for me is that some information will be sent out to the program with web service (like price, info, etc...) and then using a controller it checks the information and calls for the module, and sends the information to it. the it puts the module information to a stdclass and then using the PDO module it creates a transaction. and while the transaction is at work an insert command is sent for the database, and then we have a SELECT command and the program works well even after the insert command but while SELECT is at work , we have repetitive IDs which is the problem here:
my code:
//WSDL Creattor And Class
<?php
ini_set("soap.wsdl_cache_enabled", 1);
set_time_limit(300);
class wsdl extends Controller
{
public function index()
{
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'POST') {
$servidorSoap = new SoapServer('http://' . $_SERVER['SERVER_NAME'] . '/wsdl');
$servidorSoap->setClass('wsdl');
$servidorSoap->handle();
}
}
public function request($pin = null, $amount = 1, $callback = null, $orderid = null, $desc = null)
{
if(empty($callback))
return -10; // call back is empty.
if (empty($pin) && $result->pin != $pin)
return -1; // pin invalid
$this->Model("payment");
$au = $this->mod->Request($result, $amount, $callback, $orderid, $desc);
return $au;
}
}
payment model:
<?php
class Payment_mod extends Model
{
public function Request($gateway, $amount, $callback, $orderid, $description)
{
// using pdo module
$this->DB->CONNECT->beginTransaction();
try {
$trans = new stdClass;
$trans->gateway_id = $gateway->id;
$trans->au = str_replace('.', '_temp_', microtime(true));
$trans->price = $amount;
$trans->order_id = $orderid;
$trans->ip = $_SERVER['REMOTE_ADDR'];
$trans->time = time();
$trans->call_back = $callback;
$trans->description = $description;
$this->DB->Insert("trans", $trans); // insert into table trans …
$id = $this->DB->Fetch("trans", "`gateway_id` =" . $trans->gateway_id . " AND `price`=".$trans->price." AND time = " . $trans->time)->id; // select id from trans where …
$u = new stdClass;
$u->t_id = $id;
$this->DB->Insert("test",$u); // insert into test . it for test table for check result
$this->DB->CONNECT->commit();
} catch (Exception $e) {
$this->DB->CONNECT->rollBack();
return -9; // return unknow error.
}
return $id;
}
}
for understanding where the problem exactly is and how many times each ID repeats itself, i added a table and i got the amount of return data of SELECT and put it into the database. and when i hold the f5 key for some seconds it shows that each ID repeats nearly 9 times.
screenshot:
http://uploads.im/biWEn.jpg
note: this picture shows the amount of repeat of IDs.
where is the problem? i need this to repeat a specific ID for each call.
i did the exact thing in YII framework and i had no problem there and the progam worked exactly as i needed it to. i'd be glad if you help me.
i started using cakephp, but now i encountered a problem which i am not able to solve.
I have got the following model relations which are relevant:
Exercise hasMany Points
Student hasMany Points,
now i want to check in the studentsController if for every exercise there is a Point data set, and iff not insert a new one.
When starting with no Point datasets, the function adds a new Point dataset for the first exercise correct, but after this it only updates the erxercise_id of this dataset, instead of creating new ones.
The controller function looks like this:
public function correct($id = null) {
$this->Student->id = $id;
$this->Student->recursive = 2;
if ($this->request->is('get')) {
$data = $this->Student->Exam->Exercise->find('all');
foreach($data as $exercise)
{
$exerciseID = $exercise['Exercise']['id'];
$this->Student->Point->recursive = 0;
$foundPoints = $this->Student->Point->find('all', array('conditions' => array('exercise_id' => $exerciseID)));
if($foundPoints == null)
{
$emptyPoints = array ('Point' => array(
'exercise_id' => $exerciseID,
'student_id' => $id
)
);
$this->Student->Point->save($emptyPoints);
}
else{
}
}
}
else //POST
{
}
}
if you have to insert a data you to use create() method like this:
This is only an example, with this line you create every time a new record into your database
and save data
$this->Student->Point->create();
$this->Student->Point->save($emptyPoints);
$this->Student->Point->id = '';
$this->Student->Point->save($emptyPoints);
or
$this->Student->Point->saveAll($emptyPoints);