jQuery plugin query mySQL database for data - mysql

OK, my apologies for this 'simple' question but I've forgotten ....
Have a jQuery plugin where the data comes from a mySQL db. How do I pass the object via the plugin options - see said simple :)
e.g.
jQuery('elementName').pluginName({
elements_per_page:8,
data: // A GET function to the mySQL for the data
})
the php query is simple like this:
$sql = 'SELECT * FROM tableName';
$stmt = $dbh->prepare($sql);
$stmt->execute();
$row = $stmt->fetchAll(PDO::FETCH_OBJ);
$data = json_encode($row);
echo $_GET['callback'] . '(' . $data . ')';
I have just totally forgotten how to pass the object directly into the plugin. Oviously there is something like this but 'how':
jQuery.getJSON( "functions.php&callback=?",function(data){
return data;
})
Plugin options a bit like this
var settings = $.extend({
elements_per_page:5,
data:data,
}, options );
Thanks in advance
//// EDIT ////
If I do it by calling the data first e.g.:
jQuery.getJSON("functions.php?table=table",function(data){
return pluginTest(data)
})
AND THEN call the plugin from the function pluginTest(data) like this
function pluginTest(data){
jQuery('elementName').pluginName({
elements_per_page:8,
data:data
})
}
Obviously works (well it does :) ) BUT what I really want/would like to do is call the data from within the plugin NOT call the plugin from the data as per this edit so it is more like this
jQuery('elementName').pluginName({
elements_per_page:8,
data: // A GET function to the mySQL for the data
})`
//// END EDIT ////

Related

How to fetch data from database with 3 parameters Laravel

I'm still new to this laravel, for now I'm facing a trouble for fetching data from the database. What i want to get is when there are only one data available, the second parameters won't be executed, but if there are some data available on the second parameters, then all the data from first parameter and the second parameter will be called.
$detail = Barang_Keluar_Detail::findOrFail($id); //15
$cariid = $detail->pluck('barang_keluar_id');
$instansiquery = Barang_Keluar::where('id',$cariid)->first(); //21
$instansiid = $instansiquery->pluck('instansi_id');
$tanggal = $instansiquery->pluck('tanggal')->first();//2019-12-31
and the parameter are here
$cariinstasama = Barang_Keluar::where('id', $cariid)
->orWhere(function ($query) use($instansiid, $tanggal) {
$query->where('tanggal', "'$tanggal'")
->where('instansi_id', $instansiid);
});
Please any help will be appreciated, thank you.
Laravel query builder provides elegant way to put conditional clause using when() . You can put conditional clause on your query like this:
$cariinstasama = Barang_Keluar::where('id', $cariid)
->when($instansiid, function ($query, $instansiid) {
return $query->where('instansi_id', $instansiid);
})
->when($tanggal, function ($query, $tanggal) {
return $query->where('tanggal', $tanggal);
})->get();
For more info see https://laravel.com/docs/5.8/queries#conditional-clauses
You can try this as well.
$cariinstasama = Barang_Keluar::where('id', $cariid);
if($instansiid !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
if($tanggal !== null)
{
$cariinstasama->where('instansi_id', $instansiid);
}
$result = $cariinstasama->get();
Its not clear what exactly you want.
Are you applying more than one parameter on the query if the first parameter result gives you more than one row in the database? If yes check out my approach :
$query = new Model(); // the model you want to query
if($query->where('col1', $param1)->count() > 1) // checks if the query from the 1st parameter produces more than one row in the database
$query = $query->where( // if yes apply more parameters to the query
[
['col1', $param1],
['col2', $param2]
]
);
else
$query = $query->where('col1', $param1);
$results = $query->get();
Hope it helps....

Convert datetimes from MySQL table to ISO8601 to create JSON feed in WordPress for use with FullCalendar

I've written an action in WordPress that grabs the rows from a table and encodes them in JSON format, so I can use them with the FullCalendar javascript event calendar.
The date fields from the table need to be formatted ISO8601.
In other words, when the DB renders the date/time: 2017-08-06 10:22:20, I need it converted after the query to: 2017-08-06T10:22:20 for the date fields in the query.
I'm not concerned about timezone offsets.
My function:
add_action( 'getmyevents', 'get_my_events' );
function get_my_events( $atts = [], $content = null ) {
// Use WordPress database functions
global $wpdb;
// List of events will be stored in JSON format
$json = array();
// Query retrieves list of events
$mytable = $wpdb->prefix . "my_events";
$myids = $wpdb->get_results("SELECT * FROM " . $mytable );
// sending the encoded result to success page
echo json_encode( $myids, JSON_UNESCAPED_SLASHES );
// return JSON
return $json;
}
Can someone give me a quick, direct way to convert the datetime strings in the query to ISO8601?
Maybe you can try something like this.
Although I don't know the name of your column. Uncomment the print_r to get the column name.
foreach ($myids as $key => $row) {
// print_r($row);
$date_reformatted = strtotime($row->date_col);
$myids[$key]->date_col = date( 'c', $date_reformatted );
}
It isn't the ideal answer I was looking for, but I did come up with a working solution. Mark's suggestion about filtering during the query gave me the clue I needed for it.
add_action( 'getmyevents', 'get_my_events' );
function get_my_events( $atts = [], $content = null ) {
global $wpdb;
// Values sent via ajax to calendar from my_events table
// List of events
$json = array();
// Query that retrieves events
$mytable = $wpdb->prefix . "my_events";
$myids = $wpdb->get_results( 'SELECT id, title, url, DATE_FORMAT( start, "%Y-%m-%d\T%H:%i:%s" ) as start, DATE_FORMAT( end, "%Y-%m-%d\T%H:%i:%s" ) as end, allDay FROM ' . $mytable );
// sending the encoded result to success page
echo json_encode( $myids, JSON_UNESCAPED_SLASHES );
// return JSON
return $json;
}
However, if someone else can come up with an answer that doesn't require me to specify columns by name, that would be great. Even better would be not formatting within the query at all, but rather formatting afterward. I always like to minimize processor use by MySQL as much as possible.

Laravel 5: How to dump SQL query?

Laravel 5's built-in solution
In Laravel 5+, we can use \DB::getQueryLog() to retrieve all executed queries. Since, query logging is an extensive operation and cause performance issues so it's disabled by default in L5 and only recommend for development environments only. We can enable the query logging by using the method \DB::enableQueryLog(), as mentioned in [Laravel's documentation][1].
Problem in built-in solution
The DB::getQueryLog() function is great but sometimes we wish that it would be great if we get dump in flat SQL format, so we can copy/past it in our favorite MySQL application like phpMyAdmin or Sqlyog to execute it and debug or optimize it.
So, I need a helper function that helps me to produce dump with following additional info:
On which file and line number the dump has called.
Remove back-ticks from the query.
Flat query, so don't need to update binding parameters manually and I can copy/past SQL in phpMyAdmin etc to debug/optimize the query.
Custom Solution
Step 1: Enable Query Logging
Copy/past following block of code on top of route file:
# File: app/Http/routes.php
if (\App::environment( 'local' )) {
\DB::enableQueryLog();
}
Step 2: Add helper function
if (!function_exists( 'dump_query' )) {
function dump_query( $last_query_only=true, $remove_back_ticks=true ) {
// location and line
$caller = debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS, 1 );
$info = count( $caller ) ? sprintf( "%s (%d)", $caller[0]['file'], $caller[0]['line'] ) : "*** Unable to parse location info. ***";
// log of executed queries
$logs = DB::getQueryLog();
if ( empty($logs) || !is_array($logs) ) {
$logs = "No SQL query found. *** Make sure you have enabled DB::enableQueryLog() ***";
} else {
$logs = $last_query_only ? array_pop($logs) : $logs;
}
// flatten bindings
if (isset( $logs['query'] ) ) {
$logs['query'] = $remove_back_ticks ? preg_replace( "/`/", "", $logs['query'] ) : $logs['query'];
// updating bindings
$bindings = $logs['bindings'];
if ( !empty($bindings) ) {
$logs['query'] = preg_replace_callback('/\?/', function ( $match ) use (&$bindings) {
return "'". array_shift($bindings) . "'";
}, $logs['query']);
}
}
else foreach($logs as &$log) {
$log['query'] = $remove_back_ticks ? preg_replace( "/`/", "", $log['query'] ) : $log['query'];
// updating bindings
$bindings = $log['bindings'];
if (!empty( $bindings )) {
$log['query'] = preg_replace_callback(
'/\?/', function ( $match ) use ( &$bindings ) {
return "'" . array_shift( $bindings ) . "'";
}, $log['query']
);
}
}
// output
$output = ["*FILE*" => $info,
'*SQL*' => $logs
];
dump( $output );
}
}
How to use?
Take dump of last executed query, use just after the query execution:
dump_query();
Take dump of all executed queries use:
dump_query( false );
On which file and line number the dump has
called.
I don't understand why you need this because you always know where you called the dump function but never mind you have your solution for that.
Remove back-ticks from the query.
You don't need to remove back-ticks as the query will work in MySQL along with them also.
Flat query, so don't need to update binding parameters manually and I can copy/past SQL in phpMyAdmin etc to debug/optimize the query.
You can use vsprintf for binding parameters as:
$queries = DB::getQueryLog();
foreach ($queries as $key => $query) {
$queries[$key]['query'] = vsprintf(str_replace('?', '\'%s\'', $query['query']), $query['bindings']);
}
return $queries;
And I would suggest you to checkout this github repo squareboat/sql-doctor
I was looking for simple solution and the one below worked for me.
DB::enableQueryLog();
User::find(1); //Any Eloquent query
// and then you can get query log
dd(DB::getQueryLog());
Reference Links:
How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array
https://www.codegrepper.com/code-examples/php/dump+sql+query+laravel
Add this code in the top of your routes file.
Laravel 5.2 routes.php
Laravel 5.3+ web.php
<?php
// Display all SQL executed in Eloquent
Event::listen('Illuminate\Database\Events\QueryExecuted', function ($query) {
var_dump($query->sql);
var_dump($query->bindings);
var_dump($query->time);
echo "<br><br><br>";
});
For a Laravel 8 application it could be useful to put the following in the AppServiceProvider.php file:
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
// [...]
// Dump SQL queries on demand **ONLY IN DEV**
if (env('APP_ENV') === 'local') {
DB::enableQueryLog();
Event::listen(RequestHandled::class, function ($event) {
if ( $event->request->has('sql-debug') ) {
$queries = DB::getQueryLog();
Log::debug($queries);
dump($queries);
}
});
}
// [...]
}
Then appending &sql-debug=1 to the url will dump the queries.

Laravel Select Query within helper file

I'm coming from codeigniter background. Unlike codeigniter helper directory, i just created helper directory within app directory of Laravel. Just want to know how to execute query within this common function. Here is my codeigniter function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$output = "";
$ci =& get_instance();
$ci->db->select("*");
$ci->db->where('is_active', "Y");
$ci->db->where('is_delete', "N");
$ci->db->where('parent_id', $parent_id);
($sort_order!="")?$ci->db->order_by($sort_order, "ASC"):"";
$query = $ci->db->get('tbl_cms_menus');
foreach ($query->result() as $row){
$output .= '<option value="'.$row->$primary_key_col.'">'.$indent.$row->menu_name.'</option>';
}
return $output;
}
I tried something like this in laravel file. but this code did't give me any result. Please tell me where i'm doing wrong in this code. thanks
function databaseTable()
{
$table = DB::table('tbl_cms_menus');
$get_rows = $table->get();
$count_rows = $table->count();
if($count_rows > 0){
foreach ($get_rows as $tbl)
{
echo $tbl->menu_name;
}
}
}
This code will rot so hard that it shipped pre-rotten.
But, if you want to just.. ram it into the app all dry like that.. then add something like this to your base controller class...
$whatever = crazyChainingStuff;
foreach ($whatever ...) { $topMenu .= ... }
View::share('topMenu', $topMenu);
If you want to learn how to write code that will do less damage to your company and your clients then I recommend starting by watching Uncle Bob's "Fundamentals" videos. At least the first 5-6. http://cleancoders.com
It looks like you are trying to generate a drop-down/select with some data from your database, in this case, you should pass the data required for the drop-down/select from your controller to the view where you have written your HTML, for example, in your view, you may have a select like this:
echo Form::select('cms_menu', $cms_menu, Input::old('cms_menu'));
Or this (If you are using Blade):
{{ Form::select('cms_menu', $cms_menu, Input::old('cms_menu')) }}
From your controller you should pass the $cms_menu which should contain the menu-items as an arrtay and to populate that array you may try something like this:
$menuItems = DB::table('tbl_cms_menus')->lists('menu_name','id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
Also, you may use something like this:
// Assumed you have a Page model
$menuItems = Page::lists('menu_name', 'id');
return View::make('your_view_name', array('cms_menu' => $menuItems));
You may also read this article which is about building a menu from database using view composer (More Laravelish way). Read more about Form::select on documentation.
It was too late to give an answer. I was also from CodeIgniter background and when I learnt Laravel then first I try to find how can I write a query in Helper. My Team leader helped me.
I have converted your code in a helper function.
function show_menu($primary_key_col, $parent_id, $sort_order)
{
$query = DB::table('tbl_cms_menus')
->select('*')
->where('is_active', '=', 'Y')
->where('is_delete', '=', 'N')
->where('parent_id', '=', $parent_id);
($sort_order != "")? $query->orderBy($sort_order, "ASC") : "";
$resultData = $query->get()->toArray();
}
Here $resultData will be array format. Now, you can create a foreach loop according to your requirement.

How to see MySQL statements and error (if any) in CakePHP shell

I am using CakePHP 1.3 and writing custom shells to run mundane tasks in cronjobs. I am seeing failed Model->save() from time to time but I don't know anyway to find out what the exact problem is.
Is there a way to display the actual SQL statements executed and warning/error returned by MySQL in a CakePHP shell?
Thanks.
You can use the following SQL dump task for shells.
http://bakery.cakephp.org/articles/carcus88/2011/04/08/sql_dump_task_for_shells
One way to do this would be to watch the MySQL log file in a separate terminal.
A couple ways of doing this are listed here:
MySQL Query Logging in CakePHP
I found a way to do it. In your shell, add:
function initialize()
{
Configure::write('debug', 2);
$this->_loadDbConfig();
$this->_loadModels();
}
Then whenever you like to see the log, call this function:
function dump_sql()
{
$sql_dump = '';
if (!class_exists('ConnectionManager') || Configure::read('debug') < 2)
return false;
$noLogs = !isset($logs);
if ($noLogs)
{
$sources = ConnectionManager::sourceList();
$logs = array();
foreach ($sources as $source):
$db =& ConnectionManager::getDataSource($source);
if (!$db->isInterfaceSupported('getLog')):
continue;
endif;
$logs[$source] = $db->getLog();
endforeach;
}
if ($noLogs || isset($_forced_from_dbo_))
{
foreach ($logs as $source => $logInfo)
{
$text = $logInfo['count'] > 1 ? 'queries' : 'query';
$sql_dump .= "cakeSqlLog_" . preg_replace('/[^A-Za-z0-9_]/', '_', uniqid(time(), true));
$sql_dump .= '('.$source.') '. $logInfo['count'] .' '.$text. ' took '.$logInfo['time'].' ms';
$sql_dump .= 'Nr Query Error Affected Num. rows Took (ms)';
foreach ($logInfo['log'] as $k => $i)
{
$sql_dump .= $i['query'];
}
}
}
else
{
$sql_dump .= 'Encountered unexpected $logs cannot generate SQL log';
}
}
One other approach would be to have all your custom queries in the models/behaviors, and just calling the data/updates from shells. This would give you an extra benefit of being able to reuse those custom SQL in other parts of the project. For example, in unit tests.
In CakePHP 1.2, I was able to get the SQL queries to show up in my console output by adding a Configure::write('debug', 2); call to the bottom of the __bootstrap method in the cake/console/cake.php file.
No need to mess around with specifically calling a dump_sql function like some of these answers, I just automatically get the normal queries like at the bottom of a web page.