Symfony : How to fetch data in a table which is not an entity - ajax

I would like to know if it's possible to use Doctrine to fetch some data in a table which is not an entity.
use Doctrine\DBAL\Driver\Connection;
$connection->fetchAll("SELECT ...");
I tried to use the Connection namespace. this one is working with my entities, but not with the table i want.
This code is actually working, but i'm using PDO to connect the database to execute the query. So the Ajax request is not fast enough. And my SQL query must be prepared to avoid security breaches.
Thanks for your help
/**
* #Route("/api/search", name="map_api_search")
*/
public function search(Connection $connection, Request $request, ObjectManager $manager): Response
{
if ($ajaxRequest = $request->getContent()) {
$requestContent = json_decode($ajaxRequest, true);
$content = $requestContent["content"];
$config = new \Doctrine\DBAL\Configuration();
$connectionParams = array(
'dbname' => 'smartport',
'user' => 'root',
'password' => '',
'host' => '127.0.0.1:3306',
'driver' => 'pdo_mysql',
);
$conn = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);
// Prepare the query
$sql = "SELECT nom, lon, lat, id FROM `chimie_stations2` WHERE nom LIKE '%$content%' AND aasqa = 'PACA'";
// Execute SQL query
$stmt = $conn->query($sql);
//Prepare an array to push all the results from the query
$results = array();
// Processing...
while ($data = $stmt->fetch()) {
$results[] = $data;
}
if (($results)) {
return new JsonResponse([
'result' => true,
'results' => json_encode($results),
]);
} else {
return new JsonResponse([
'result' => false,
]);
}
}
}

If you want to prepare your SQL query :
public function myFunction(EntityManager $entityManager)
{
$connection = $entityManager->getConnection();
$sql = 'SOME SQL HERE';
$stmt = $connection->prepare($sql);
$stmt->execute();
$stmt->fetchAll();
}

Related

Get Raw SQL of Insert Statement

I am looking for a way to get the correct SQL queries for an INSERT statement. I'm having to export this data for use in another (non-laravel) system. The post at How to get the raw SQL for a Laravel delete/update/insert statement? got me part of the way there but my queries are still parameterized:
Post::all()->each(function($post)
{
$builder = DB::table('posts');
$insertStatement = $builder->getGrammar()->compileInsert($builder->select(['created_at', 'title']), [
'created_at' => $post->created_at,
'title' => $post->title
]);
Storage::disk('sql')->append('posts-latest.sql', $insertStatement);
dump($insertStatement);
}
this results in...
insert into `posts` (`created_at`, `title`) values (?, ?)
So I've managed to set the fields to be updated but how to swap out the parameters for real values?
You can do this:
Post::all()->each(function($post){
$builder = DB::table('posts');
$grammar = $builder->getGrammar();
$values = [
'created_at' => $post->created_at,
'title' => $post->title
];
$table = $grammar->wrapTable($builder->from);
if (!is_array(reset($values))) {
$values = [$values];
}
$columns = $grammar->columnize(array_keys(reset($values)));
$parameters = collect($values)->map(function ($record) use ($grammar) {
$record = array_map(function($rec){
$rec = str_replace("'", "''", $rec);
return "'$rec'";
},array_values($record));
return '('.implode(', ', $record).')';
})->implode(', ');
$insertStatement = "insert into $table ($columns) values $parameters";
// $insertStatement should contains everything you need for this post
});
I ended up discovering DB::pretend which will generate the query without running it. Then it's a case of substitution. It seems that there is no way to get the raw SQL without substitution due to the use of parameters.
Post::all()->each(function($post)
{
$builder = DB::table('posts');
$query = DB::pretend(function() use ($builder, $post)
{
return $builder->insert([
'created_at' => $post->created_at,
'title' => $post->title,
'content' => $post->content,
'featured_image_link' => $post->featured_image_link,
'slug' => $post->slug
]);
});
$bindings = [];
collect($query[0]['bindings'])->each(function($binding) use (&$bindings)
{
$binding = str_replace("'", "\\'", $binding);
$bindings[] = "'$binding'";
});
$insertStatement = Str::replaceArray('?', $bindings, $query[0]['query']);
Storage::disk('sql')->append('posts-latest.sql', $insertStatement.';');
});

Laravel isDirty method mass assignment

My code is saving data of only one field(efirst) if it's changed by the isDirty() method, and it's working correctly. How can I achieve the same result if I have ten fields without writing each field name?
Controller:
public function update(TeacherRequest $request, $id)
{
$teacher = Teacher::find($id);
$teacher->efirst = $request->efirst;
if ($teacher->isDirty()) {
$new_data = $teacher->efirst;
$old_data = $teacher->getOriginal('efirst');
if ($teacher->save()) {
$teacher->update($request->except('qual_id', 'id', 'profile_pic'));
DB::table('teacher_logs')->insert(
[
'user_id' => $user->id,
'teacher_id' => $teacher->id,
'old_value' => $old_data,
'new_value' => $new_data,
]);
}
}
}
If you don't want to write $teacher->field = $request->value; a bunch of times, you may use a loop:
foreach($request->except("_token") AS $field => $value){
$teacher->{$field} = $value;
}
if($teacher->isDirty()){
$new_data = [];
$old_data = [];
foreach($request->except("_token") AS $field => $value){
$new_data[$field] = $value;
$old_data[$field] = $teacher->getOriginal($field);
}
}
Note: You'll need to convert $new_data and $old_data to arrays so you can reference each field and value properly, and do some additional logic on the insert of your teacher_logs table to handle, but that should give you an idea.

laravel DB update get changes column

i want to save log of changes when i update something on the database.
there is elegant way to get the column that will be updated (just if there is change).
i want to save the old column value in log..
for example:
$updateUser = DB::table('users')->where('id','1')->update(array('email' => 'new#email.com', 'name' => 'my new name'));
from this i want to get back the old email was in database (if changed) and the old name (again, only if changed)
thanks!
As others have mentioned, Eloquent is a great way to go if using Laravel. Then you can tap directly into Laravel's events using Observers. I have used a method very similar to what is below. Of course, you would need to set up Models for User and AuditLog.
See more info regarding Observers.
https://laravel.com/docs/5.8/eloquent#observers
In Controller Method
$user = User::find(1);
$user->update([
'email' => 'new#email.com',
'name' => 'my new name'
]);
App/Providers/EventServiceProvider.php
class EventServiceProvider extends ServiceProvider
{
// ...
public function boot()
{
User::observe(UserObserver::class);
}
}
App/Observers/UserObserver.php
class UserObserver
{
/**
* The attributes to exclude from logging.
*
* #var array
*/
protected $except = [
'created_at',
'updated_at'
];
/**
* The attributes to mask.
*
* #var array
*/
protected $masked = [
'password',
];
/**
* Listen for model saved event.
*
* #var array
*/
public function saved($model)
{
// search for changes
foreach ($model->getChanges() as $key => $new_value) {
// get original value
$old_value = $model->getOriginal($key);
// skip type NULL with empty fields
if ($old_value === '' && $new_value === null) {
continue;
}
// attribute not excluded and values are different
if (!in_array($key, $this->except) && $new_value !== $old_value) {
// mask designated fields
if (in_array($key, $this->masked)) {
$old_value = '********';
$new_value = '********';
}
// create audit log
AuditLog::create([
'user_id' => auth()->user()->id,
'model_id' => $model->id,
'model' => (new \ReflectionClass($model))->getShortName(),
'action' => 'update',
'environment' => config('app.env'),
'attribute' => $key,
'old_value' => $old_value,
'new_value' => $new_value,
]);
}
}
}
}
I hope this helps!
EDIT: See comment regarding update.
I will suggest 2 options:
1) to use the Eloquent model on every changes,
and then to use the existing methods like :
model->isDirty()
model->getChanges()
you can implement it on the model life cycle of updating / updated events listeners
more information and example you can see here:
https://laravel.com/docs/5.8/events
https://medium.com/#JinoAntony/10-hidden-laravel-eloquent-features-you-may-not-know-efc8ccc58d9e
https://laravel.com/api/5.3/Illuminate/Database/Eloquent/Model.html
2) if you want to log changes even if you are running regular queries and not only via model life cycle,
you can use MySql Triggers on every table updates and then to check OLD vs NEW and insert directly to the log changes db
more information you can find here:
https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html
MySQL Trigger after update only if row has changed
Why not just something like this:
$changeArr = ['email' => 'new#email.com', 'name' => 'my new name'];
$id = 1;
$table = 'users';
foreach($changeArr as $key => $value){
DB::table('updateTable')->insert(['table' => $table, 'id' => $id, 'col' => $key, 'oldVal' => $value]);
}
$updateItem = DB::table($table)->where('id', $id)->update($changeArr);
Check for the changed values and update accordingly, saving the old values to log table if changed
$newData = ['email' => 'new#email.com', 'name' => 'my new name'];
$user = App\User::find(1);
$log = [];
if ($user->email != $newData['email']) {
$log['user_id'] = $user->id;
$log['email'] = $user->email;
$user->email = $newData['email'];
} elseif ($user->name != $newData['name']) {
$log['name'] = $user->name;
$user->name = $newData['name'];
$logged = DB::table('log')->insert($log);
}
$updateUser = $user->save();
//try this. hpe it helps out:
function Update(Request $request, $id)
{
$dbrecord = DB::table('users')->where('id',$id)->first();
$oldemail = $dbrecord->email;
$oldname = $dbrecord->name;
if(($oldemail==$request->input('email'))&&($oldname==$request->input('name')))
{
//do nothing
}
elseif(($oldemail!=$request->input('email'))or($oldname!=$request->input('name')))
{
$updateUser = DB::table('users')->where('id',$id)->update(array('email' => $request->input('email'), 'name' => $request->input('name')));
if($updateUser)
{
DB::table('log')->where('id',$id)->insert(array('email' => $oldemail, 'name' => $oldname));
}
}
}

codeigniter how to store real time data

public function insert_employee($fldCompanyStringID) {
$fldCompanyID = getCoompanyByStringID($fldCompanyStringID)->fldCompanyID;
$data = array(
'fldUserFName' => $this->input->post('fldUserFName'),
'fldUserBankAccountNumber' => $this->input->post('fldUserBankAccountNumber')
);
$data2 = array(
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
if ($this->db->insert('tblUser', $data)&& $this->db->insert(' tblWorkHistory', $data2)) {
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
}
The tblUser table auto generates a userID. I want to take that userID and store it into the tblWorkHistory table **
Here CodeIgniter transactions will help you.
https://www.codeigniter.com/user_guide/database/transactions.html
Please use this code --
<?php
public function insert_employee($fldCompanyStringID) {
$this->db->trans_start();
$fldCompanyID = getCoompanyByStringID($fldCompanyStringID)->fldCompanyID;
/* Insert User */
$data = array(
'fldUserFName' => $this->input->post('fldUserFName'),
'fldUserBankAccountNumber' => $this->input->post('fldUserBankAccountNumber')
);
$this->db->insert('tblUser', $data)
$insert_id = $this->db->insert_id();
/* Insert Work History */
$data2 = array(
'userID' => $insert_id,
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
$this->db->insert('tblWorkHistory', $data2)
/* Manage Transaction */
$this->db->trans_complete();
if ($this->db->trans_status() === FALSE){
$this->session->set_flashdata('error_msg', 'Failed, please try again');
}else{
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
}
?>
$this->db->insert_id() is used to get the last insert auto increment id data.
$this->db->insert('tblUser', $data);
$insert_id = $this->db->insert_id();
if($insert_id) {
$data2 = array(
'userID' => $insert_id,
'fldWorkHistoryCompanyName' => $this->input->post('fldWorkHistoryCompanyName')
);
if ($this->db->insert(' tblWorkHistory', $data2)) {
$this->session->set_flashdata('success_msg', 'New Employee is inserted');
}
} else {
$this->session->set_flashdata('error_msg', 'Something went wrong');
}

Laravel 4 code organization

I have some questions to Laravel 4 code organization. I am not the best "clean coder" and come from the Java world and sometimes my PHP / Laravel 4 code looks terrible. I post an example here from my controller:
public function postCreate()
{
$input = array(
'title' => Binput::json('title'),
'gender' => Binput::json('gender'),
'first' => Binput::json('first'),
'last' => Binput::json('last'),
'birthdate' => Binput::json('birthdate'),
'birthplace' => Binput::json('birthplace'),
'citizenship' => Binput::json('citizenship'),
'organizationId' => Binput::json('organizationId'),
'typeId' => Binput::json('typeId'),
'email' => Binput::json('email'),
'phone_private' => Binput::json('phone_private'),
'phone_mobile' => Binput::json('phone_mobile'),
'address_street' => Binput::json('address.street'),
'address_postcode' => Binput::json('address.postcode'),
'address_city' => Binput::json('address.city'),
'address_country' => Binput::json('address.country'),
'educations' => Binput::json('educations'),
'selectedLanguages' => Binput::json('selectedLanguages'),
'work' => Binput::json('work'),
);
$rules = array (
'gender' => 'required|max:1',
'first' => 'required|min:2',
'last' => 'required|min:2',
'birthdate' => 'required',
'organizationId' => 'required',
'typeId' => 'required',
'email' => 'required|email',
);
$v = Validator::make($input, $rules);
if ($v->fails() || empty($input['educations']))
{
$data = array("flash" => 'Firstname, Lastname, Birthdate, Email and at least 1 entry in Educations required.');
return Response::json($data, 500);
}
try {
DB::connection()->getPdo()->beginTransaction();
$member = new Member();
$member->title = $input['title'];
$member->gender = $input['gender'];
$member->first = $input['first'];
$member->last = $input['last'];
$member->birthdate = $input['birthdate'];
$member->birthplace = $input['birthplace'];
$member->citizenship = $input['citizenship'];
$work = new Work();
$work->working = $input['work']['working'];
if($input['work']['working'] == 1){
$work->branch = $input['work']['branch'];
$work->company = $input['work']['company'];
}
$work->save();
$member->work()->associate($work);
$member->save();
foreach($input['educations'] as $eduInput){
$edu = new Education();
$edu->degree = $eduInput['degree'];
if(!empty($eduInput['course'])){
$edu->course = $eduInput['course'];
}
$edu->term = $eduInput['term'];
$edu->completion = $eduInput['completion'];
if(!empty($eduInput['faculty'])){
try{
$faculty = Faculty::findOrFail($eduInput['faculty']['id']);
$edu->faculty()->associate($faculty);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}
if($eduInput['institutionId'] == 0){
// University
try{
$university = University::findOrFail($eduInput['university']['id']);
$edu->university()->associate($university);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}else{
// Freetext
$edu->institution = $eduInput['institution'];
}
$edu->save();
$member->educations()->save($edu);
}
foreach($input['selectedLanguages'] as $languageInput){
try{
$lang = Language::findOrFail($languageInput['id']);
$member->languages()->attach($lang);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
}
try{
$memberType = MemberType::findOrFail($input['typeId']);
$member->memberType()->associate($memberType);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
try{
$organization = Organization::findOrFail($input['organizationId']);
$member->organizations()->attach($organization);
}catch (\Illuminate\Database\Eloquent\ModelNotFoundException $e){
}
$email = new Email();
$email->email = $input['email'];
$email->primary = true;
$member->emails()->save($email);
// If input for phone is empty
$phone = new Phone();
$phone->phone = $input['phone_private'];
$phone->phoneType()->associate(PhoneType::find(PhoneType::PRIVATE_PHONE));
$member->phones()->save($phone);
$phone = new Phone();
$phone->phone = $input['phone_mobile'];
$phone->phoneType()->associate(PhoneType::find(PhoneType::MOBILE_PHONE));
$member->phones()->save($phone);
$address = new Address();
$address->street = $input['address_street'];
$address->postcode = $input['address_postcode'];
$address->city = $input['address_city'];
$address->country = $input['address_country'];
$address->member()->associate($member);
$address->save();
DB::connection()->getPdo()->commit();
}catch (\PDOException $e) {
DB::connection()->getPdo()->rollBack();
return Response::json("Error while writing to database.", 500);
}
$member->load('emails');
$data = array("flash" => 'Member created successfully.');
return Response::json($data, 200);
}
This is an example from my controller.
Is it normal to get all parameters in this way. It takes much of space.
Can I move my database transaction elsewhere and not storing in the controller ?
In general where to store the code that manages logic ? In the controller ? In the
model ?
Your controller actions are just a sort of middleware in the sense that in there you should not put any of your business logic. a few pointers I can provide:
you can get all the json input with Input::json()->all() which returns an array so you can operate it.
Validation rules are another responsibility so it should be abstracted in another class that you call from the controller, it also may be well suited in your models(or entities).
To help you understand how can you use another class inside your controllers you should look for dependency injection in the laravel docs.
if you can get access to this book https://leanpub.com/laravel by Laravel's creator it will help your understanding of code organization and class responsibilities even outside laravel

Resources