I have query in php
select
c.*,
CONCAT(c.first_name, ' ' ,c.middle_name, ' ' ,c.last_name) as name,
r.paid_amount as total_amount_paid,
r.emi_date as emi_date_from_reciept,
ltc.loan_amount as total_remaining_loan_amount ,
ltc.emi_date as emi_loan_date,
ltc.no_of_month as num_of_months_from_ltc
FROM loan_to_customer ltc
LEFT JOIN customer c ON ltc.customer_id = c.customer_id
LEFT JOIN receipt r ON r.customer_id = c.customer_id
WHERE c.cust_mobile = '$cust_mobile' OR c.unique_no = '$unique_no'
I am getting this error
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1`
I am getting this error while my table is empty.
If I execute this on phpmyadmin it simply run and success.
My php code is like this
<?php
include "connection.php";
extract($_REQUEST);
$data = array();
$resArr = array();
$query = customSelectQuery("select c.*, CONCAT(c.first_name, ' ' ,c.middle_name, ' ' ,c.last_name) as name,r.paid_amount as total_amount_paid,
r.emi_date as emi_date_from_reciept, ltc.loan_amount as total_remaining_loan_amount ,
ltc.emi_date as emi_loan_date, ltc.no_of_month as num_of_months_from_ltc FROM loan_to_customer ltc
LEFT JOIN customer c ON ltc.customer_id = c.customer_id
LEFT JOIN receipt r ON r.customer_id = c.customer_id
WHERE c.cust_mobile = '$cust_mobile' OR c.unique_no = '$unique_no'");
if (isset($query)) {
$ltc_data = array();
foreach ($query as $row) {
$ltc_data = array(
'loan_amount' => $row['loan_amount'],
'total_remaining_loan_amount' => $row['total_remaining_loan_amount'],
'no_of_month' => $row['no_of_month'],
"num_of_months_from_ltc"=>$row['num_of_months_from_ltc'],
"emi_date_from_reciept" => $row['emi_date_from_reciept'],
"customer_id"=>$row['customer_id'],
);
}
}
$customer_id = $ltc_data['customer_id'];
$query1 = customSelectQuery("SELECT * FROM receipt WHERE customer_id = $customer_id");
$penalty_amoount = '100';
$paid_emi_date = array();
foreach ($query1 as $row1) {
$paid_emi_date[] = array('date'=>$row1['emi_date'],'amount'=>$row1['paid_amount'], 'penalty_amoount'=>$penalty_amoount);
}
$loan_amount = $ltc_data['loan_amount'];
$total_remaining_loan_amount = $ltc_data['total_remaining_loan_amount'];
$total_amount_paid = $loan_amount - $total_remaining_loan_amount;
$no_of_month = $ltc_data['no_of_month'];
$num_of_months_from_ltc = $ltc_data['num_of_months_from_ltc'];
$total_paid_emi_month = $no_of_month - $num_of_months_from_ltc;
$penalty_amoount1 = '20';
if (sizeOf($query) > 0) {
$d = array();
foreach ($query as $row) {
// $output = [];
foreach ( explode(',', $row['emi_loan_date']) as $date ) {
$output[] = ['date' => $date, 'emi_amount' => $row['emi_amount'], 'penalty_amoount'=>$penalty_amoount1];
}
$emi_date1 = $output[0]['date'];
$emi_a = $output[0]['emi_amount'];
$p_amo = $output[0]['penalty_amoount'];
$f_a = $emi_a + $p_amo;
$d[] = array(
"name" => $row['name'],
"Loan_Account_No" => $row['unique_no'],
"product_amount"=> $row['product_amount'],
"num_of_months" => $row['num_of_months'],
"no_of_month" => $no_of_month,
"loan_amount" => $row['loan_amount'],
"total_paid_emi_month" =>$total_paid_emi_month,
'total_amount_paid' => $total_amount_paid,
'total_remaining_loan_amount' => $row['total_remaining_loan_amount'],
"pending_emi_amount"=>$f_a,
"pending_emi_date"=>$emi_date1,
// "emi_date1" => explode(',', $row['emi_loan_date']),
"emi_date1" =>$output,
"paid_emi_date"=> $paid_emi_date,
"start_emi_date"=> $row['loan_date'],
"emi_amount"=> $row['emi_amount'],
// "emi_pending_amount"=>
);
}
}
if($d === null){
$d = " ";
$message = "not found loan data.";
}
$resArr = array("success" => 1, "data" => $d, "message" => $message);
header('Content-Type: application/json');
echo str_replace("\/", "/", json_encode($resArr, JSON_UNESCAPED_UNICODE));
?>
replace '$cust_mobile' by '\''.$cust_mobile.'\'' and '$unique_no' by '\''.$unique_no.'\''. Because $cust_mobile and $unique_no are variables
select c.*, CONCAT(c.first_name, ' ' ,c.middle_name, ' ' ,c.last_name) as name,r.paid_amount as total_amount_paid,
r.emi_date as emi_date_from_reciept, ltc.loan_amount as total_remaining_loan_amount ,
ltc.emi_date as emi_loan_date, ltc.no_of_month as num_of_months_from_ltc FROM loan_to_customer ltc
LEFT JOIN customer c ON ltc.customer_id = c.customer_id
LEFT JOIN receipt r ON r.customer_id = c.customer_id
WHERE c.cust_mobile = '\''.$cust_mobile.'\'' OR c.unique_no = '\''.$unique_no.'\''
Related
The following php code allows me to retrieve from a database the information of the orders of the day in order to export them in a csv file.
However I also have a file ArticleStock.csv which contains information on the products: ID and Name but which are different from those present in the database. I found a way to link the two by adding the IDs from the ArticleStock file to the product reference field.
Unfortunately this does not work well because the following program outputs a csv file with only the corresponding value found and not all the others
<?php
require_once 'dbconfig.php';
try {
$pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
$sql = 'SELECT o.id_order ,
c.id_customer, c.firstname, c.lastname,
a.address1, a.address2, a.postcode,
a.city,a.phone,
c.email,
a.phone_mobile,
od.product_id, od.product_name,
p.reference,
od.product_quantity, od.product_price,
o.total_paid_tax_incl,
c.id_customer,
op.date_add, op.amount, op.payment_method
FROM mod582_orders o
INNER JOIN mod582_customer c ON o.id_customer = c.id_customer
INNER JOIN mod582_address a ON o.id_address_delivery = a.id_address
INNER JOIN mod582_order_detail od ON o.id_order = od.id_order
INNER JOIN mod582_order_payment op ON o.reference = op.order_reference
INNER JOIN mod582_product p ON p.id_product = od.product_id
WHERE CAST(o.date_add AS DATE) like "2022-12%";';
$r = $pdo->query($sql);
$tab = [];
$tab[] = ['ORDNOORDER', 'ORDREFCUSORDER', 'ORDNOCOSTNUMBER', 'ORDNOCUSTOMER', 'ORDCUSTOMERCODE', 'ORDCUSCAT', 'ORDTYPE', 'ORDCURRENCY', 'ORDCURRENCYRATE', 'ORDDESIGNATION',
'ORDREPCODE', 'ORDPORT', 'ORDPORTTYPE', 'ORDPORTRATE', 'DEONOORDER', 'DEOCOMMENT', 'DEOCOUNTRY', 'DEONAME', 'DEOFIRSTNAME', 'DEOADDRESS1', 'DEOADDRESS2', 'DEOZIPCODE', 'DEOCITY',
'DEOPHONE', 'DEOMAIL', 'DEOPHONEPORTABLE', 'ODLNOORDER', 'ODLNOORDERLINE', 'ODLNOARTICLE', 'ODLARTDESIGN', 'REFERENCEPRODUIT', 'ODLQUANTITYORDER', 'ODLTTCCURUPRICE', 'ODLCODEPARCELLEFLEU',
'PAYNUMPAYMENT', 'PAYNOCUSTOMER', 'PAYNOORDER', 'PAYNOCURRENCY', 'PAYDATEPAYMENT', 'PAYPAYMENTTTCCUR', 'PAYCURRENCYRATE', 'PAYCONTREPARTIE'];
$odrline = 0; // start with zero, as incremented before first written out
$prevordernumber = 0; // pick a number that is not a valid order number
$file = fopen("ArticlesStock.csv", "r");
$rowcsv = 0;
while (!feof($file)) {
$thisLine = fgets($file);
$CSVData[$rowcsv] = explode(";", $thisLine);
$rowcsv++;
}
fclose($file);
$numRows = sizeof($CSVData);
$rowcsv = 0;
while ($rs = $r->fetch(PDO::FETCH_ASSOC)) {
$refproduit = $rs['reference'];
while ($rowcsv < $numRows) {
if ($CSVData[$rowcsv][0] == $refproduit) {
$idproduct = $CSVData[$rowcsv][0];
$nameproduct = $CSVData[$rowcsv][2];
if ($prevordernumber != $rs['id_order']) {
$odrline++;
$baseDate = strtotime($rs['date_add']);
$formatDate = date("d/m/Y", $baseDate);
$tab[] = [$rs['id_order'], $rs['id_order'], '17', '', 'AAA' . $rs['id_customer'], 'DET', 'O', 'EUR', '1', '', '115', 'D', 'P', '17', $rs['id_order'], '', 'FRA', $rs['firstname'],
$rs['lastname'], $rs['address1'], $rs['address2'], $rs['postcode'], $rs['city'], $rs['phone'], $rs['email'], $rs['phone_mobile'], $rs['id_order'], $odrline,
$idproduct, $nameproduct, $rs['reference'], $rs['product_quantity'], $rs['product_price'], '', '', '', $rs['id_order'], 'EUR', $formatDate, $rs['amount'], '1', 'VIR'];
} else {
$tab[] = [$rs['id_order'], $rs['id_order'], '17', '', 'AAA' . $rs['id_customer'], 'DET', 'O', 'EUR', '1', '', '115', 'D', 'P', '17', $rs['id_order'], '', 'FRA', $rs['firstname'],
$rs['lastname'], $rs['address1'], $rs['address2'], $rs['postcode'], $rs['city'], $rs['phone'], $rs['email'], $rs['phone_mobile'], $rs['id_order'], $odrline,
$rs['product_id'], $rs['product_name'], $rs['reference'], $rs['product_quantity'], $rs['product_price'], '', '', '', $rs['id_order'], '', '', '', ''];
}
}
$rowcsv++;
}
$prevordernumber = $rs['id_order'];
}
// write $tab to file
$date = date('d-m-y');
$fichier_csv = new SplFileObject('Vinistoria/Out/Commande/commande_STOCK_' . $date . '.csv', 'w');
foreach ($tab as $ligne) {
$fichier_csv->fputcsv($ligne, ';');
}
} catch (PDOException $e) {
die("Could not connect to the database $dbname :" . $e->getMessage());
}
CSV return by my code :
And what i need :
So i need to replace my csv file ODLNOARTICLE and ODLARTDESIGN by the IDs and Names of products present in the file ArticleStock whose ID is equal to the reference field of my products recovered by my SQL query
I've been asked to create a custom plugin displays course overview (course id, course name, enrolled and completed) through API. There is a report_completionoverview plugin that I can refer to and basically wanna retrieve exactly the same list via Moodle API in JSON format.
I'm trying to create a local plugin based on moodle documentation (https://docs.moodle.org/dev/Adding_a_web_service_to_a_plugin) and other default plugins, but having difficulty to debug.
* modified folder name to match plugin name *
I've Created
local/get_completion_overview/db/service.php
local/get_completion_overview/lang/en/local_get_completion_overview.php
local/get_completion_overview/externallib.php
local/get_completion_overview/version.php
Successfully installed the plugin without error in Moodle, but the plugin is not listed in the function.
I honestly think that my code is not right (and it is messy since I've copied from different sources), but don't know how to debug it.
Can anyone please let me know if you know how?
I also attach local/completionview/externallib.php (I'm sure this is causing the issue I believe).
Any help or idea or comment would be appreciated.
Thanks a lot!
<?php
require_once($CFG->libdir . "/externallib.php");
require_once("lib.php");
class local_get_completion_overview_external extends external_api {
public static function get_completion_overview_parameters() {
return new external_function_parameters(
array(
'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
id: course id
ids: comma separated course ids
shortname: course short name
idnumber: course id number
category: category id the course belongs to
', VALUE_DEFAULT, ''),
'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
)
);
}
public static function get_completion_overview($field = '', $value = ''){
global $CFG, $DB;
require_once($CFG->dirroot . '/course/lib.php');
require_once($CFG->libdir . '/filterlib.php');
$params = self::validate_parameters(self::get_completion_overview_parameters(),
array(
'field' => $field,
'value' => $value,
)
);
$sql = "SELECT DISTINCT cr.id AS courseid, cr.fullname AS coursename,
COUNT(DISTINCT ra.id ) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr
JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON cc.course = cr.id
GROUP BY cr.fullname, cr.id
ORDER BY coursename";
$warnings = array();
if (empty($params['field'])) {
$courses = $DB->get_records_sql($sql, array());
} else {
switch ($params['field']) {
case 'id':
case 'category':
$value = clean_param($params['value'], PARAM_INT);
break;
case 'ids':
$value = clean_param($params['value'], PARAM_SEQUENCE);
break;
case 'shortname':
$value = clean_param($params['value'], PARAM_TEXT);
break;
case 'idnumber':
$value = clean_param($params['value'], PARAM_RAW);
break;
default:
throw new invalid_parameter_exception('Invalid field name');
}
if ($params['field'] === 'ids') {
$courses = $DB->get_records_list('course', 'id', explode(',', $value), 'id ASC');
} else {
$courses = $DB->get_records('course', array($params['field'] => $value), 'id ASC');
}
}
if(!empty($courses)){
$coursesdata = array();
$currentcourseid = null;
$course = null;
foreach($courses as $completion) {
$context = context_course::instance($course->id);
$crs = array();
$crs['courseid'] = $completion->courseid;
$crs['coursename'] = (string)$completion->coursename;
$crs['enrols'] = $completion->enrols;
$crs['completed'] = $completion->completed;
try {
self::validate_context($context);
} catch (Exception $e) {
continue;
}
if(is_null($currentcourseid) || ($completion->courseid != $currentcourseid)) {
if(!is_null($course)) {
$coursesdata[] = $course;
}
$course = array();
$course['courseid'] = $completion->courseid;
}
$course['courseid'][] = $crs;
$currentcourseid = $completion->courseid;
}
if(!is_null($course)){
$coursesdata[] = $course;
}
$courses->close();
}
$result = array();
$result['course'] = $coursesdata;
return $result;
}
public static function get_completion_overview_returns() {
return new external_single_structure(
array(
'course' => new external_multiple_structure(self::get_completion_overview(), 'list of courses completion')
)
);
}
}
** service.php
<?php
$functions = array(
'local_get_completion_overview' =>
array('classname' => 'local_get_completion_overview_external',
'methodname' => 'get_completion_overview',
'classpath' => 'local/get_completion_overview/externallib.php',
'description' => 'Get course completion overview',
'type' => 'read',
'capabilities'=> array(), //optional, useful to let the administrator know what potential capabilities the user 'could' need
'services' => array(MOODLE_OFFICIAL_MOBILE_SERVICE),
),
);
$services = array(
'get completion overview' => array( //the name of the web service
'functions' => array ('local_get_completion_overview'), //web service functions of this service
'requiredcapability' => '', //if set, the web service user need this capability to access
//any function of this service. For example: 'some/capability:specified'
'restrictedusers' =>0, //if enabled, the Moodle administrator must link some user to this service
//into the administration
'enabled'=>1, //if enabled, the service can be reachable on a default installation
)
);
service.php should be services.php.
After fixing the filename, it appears in Moodle as function, however having an issue to load the function.
Undefined property: stdClass::$id in
/Users/lucy/Sites/moodle/local/get_completion_overview/externallib.php
on line 84
which is
$context = context_course::instance($completion->id);
in foreach block.
also,
Debug info: SELECT id,category FROM {course} WHERE id IS NULL
[array (
)]
Error code: invalidrecord
Stack trace:
line 1562 of /lib/dml/moodle_database.php: dml_missing_record_exception thrown
line 1538 of /lib/dml/moodle_database.php: call to moodle_database->get_record_select()
line 6822 of /lib/accesslib.php: call to moodle_database->get_record()
line 84 of /local/get_completion_overview/externallib.php: call to context_course::instance()
line 138 of /local/get_completion_overview/externallib.php: call to local_get_completion_overview_external::get_completion_overview()
line 124 of /lib/externallib.php: call to local_get_completion_overview_external::get_completion_overview_returns()
line 219 of /webservice/renderer.php: call to external_api::external_function_info()
line 121 of /admin/webservice/service_functions.php: call to core_webservice_renderer->admin_service_function_list()
Increment version number within version.php file. It will trigger moodle for update. Then you should do few updates in moodle. After that you shoudl see the listing
This works as expected. I've changed the permission to has_capability('moodle/site:config', $context);
I'm posting my solution in case someone runs into the same issue.
<?php
require_once('../../config.php');
require_once($CFG->libdir . "/externallib.php");
// require_once('../lib/externallib.php');
// require_once("lib.php");
class local_get_completion_overview_external extends external_api {
public static function get_completion_overview_parameters() {
return new external_function_parameters(
array(
'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
id: course id', VALUE_DEFAULT, ''),
'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
)
);
}
public static function get_completion_overview($field='', $value=''){
global $CFG, $DB;
require_once($CFG->dirroot . '/course/lib.php');
$params = self::validate_parameters(self::get_completion_overview_parameters(),
array(
'field' => $field,
'value' => $value,
)
);
$sql = "SELECT DISTINCT cr.id AS courseid,
cr.fullname AS coursename,
COUNT(DISTINCT ra.id ) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr
JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON cc.course = cr.id
GROUP BY cr.fullname, cr.id
ORDER BY coursename";
$warnings = array();
$coursesdata = array();
$requestedcourseids = $params['value'];
if (empty($params['field'])) {
$courses = $DB->get_records_sql($sql, array());
} else {
$value = clean_param($params['id'], PARAM_INT);
if (count($value) > 0) {
$placeholders = array();
$sql_2 = "SELECT DISTINCT cr.id AS courseid,
cr.fullname AS coursename,
COUNT(DISTINCT ra.id) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON (cc.course = cr.id)
WHERE cr.id = ".$requestedcourseids." GROUP BY cr.fullname, cr.id";
$courses = $DB->get_records_sql($sql_2, $placeholders);
}
}
if(!empty($courses)) {
$currentcourseid = null;
$course = null;
foreach($courses as $completion) {
$context = context_system::instance();
has_capability('moodle/site:config', $context);
if(is_null($currentcourseid) || ($completion->courseid != $currentcourseid)) {
if(!is_null($course)) {
$coursesdata[] = $course;
}
$course = array();
$course['courseid'] = $completion->courseid;
$course['coursename'] = $completion->coursename;
$course['enrols'] = $completion->enrols;
$course['completed'] = $completion->completed;
$course['totalcourses'] = count($course);
}
$currentcourseid = $completion->courseid;
}
if(!is_null($course)){
$coursesdata[] = $course;
}
} else {
$warning = array();
$warning['item'] = 'course';
$warning['itemid'] = $requestedcourseids;
$warning['warningcode'] = '1';
$warning['message'] = 'No course found';
$warnings[] = $warning;
}
$result['course'] = $coursesdata;
$result['warnings'] = $warnings;
return $result;
}
public static function get_completion_overview_returns() {
return new external_single_structure(
array(
'course' => new external_multiple_structure(
new external_single_structure(
array(
'courseid' => new external_value(PARAM_INT, 'description'),
'coursename' => new external_value(PARAM_TEXT, ''),
'enrols' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
'completed' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
'totalcourses' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
)
)
),
'warnings' => new external_warnings()
)
);
}
}
I am trying to pull each course completion data through API.
Pulling all data and the course data by entering courseid working okay, but when I enter courseid doesn't exist in Moodle, it doesn't return the warning message.
courseid 5 doesn't exist and it should throw warning messages but it returns an error.
Looks like it recognises whether $courseid is empty or not and shows the right value based on entered request.
I've looked at other plugin files and saw how other people passed the warning message in their code, it looks the same and I can't figure out why this doesn't throw the error message.
Am I missing importing a class maybe?
Any help would be appreciated.
Here is my code.
class local_get_completion_overview_external extends external_api {
public static function get_completion_overview_parameters() {
return new external_function_parameters(
array(
'field' => new external_value(PARAM_ALPHA, 'The field to search can be left empty for all courses or:
id: course id', VALUE_DEFAULT, ''),
'value' => new external_value(PARAM_RAW, 'The value to match', VALUE_DEFAULT, '')
)
);
}
public static function get_completion_overview($field='', $value=''){
global $CFG, $DB;
require_once($CFG->dirroot . '/course/lib.php');
$params = self::validate_parameters(self::get_completion_overview_parameters(),
array(
'field' => $field,
'value' => $value,
)
);
$sql = "SELECT DISTINCT cr.id AS courseid,
cr.fullname AS coursename,
COUNT(DISTINCT ra.id ) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr
JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON cc.course = cr.id
GROUP BY cr.fullname, cr.id
ORDER BY coursename";
$warnings = array();
$requestedcourseids = $params['value'];
if (empty($params['field'])) {
$courses = $DB->get_records_sql($sql, array());
} else {
$value = clean_param($params['id'], PARAM_INT);
if (count($value) > 0) {
$placeholders = array();
$sql_2 = "SELECT DISTINCT cr.id AS courseid,
cr.fullname AS coursename,
COUNT(DISTINCT ra.id) AS enrols,
COUNT(DISTINCT cc.timecompleted) AS completed
FROM {course} cr JOIN {context} ct ON ( ct.instanceid = cr.id )
LEFT JOIN {role_assignments} ra ON ( ra.contextid = ct.id ) and ra.roleid = 5
LEFT JOIN {course_completions} cc ON (cc.course = cr.id)
WHERE cr.id = ".$requestedcourseids." GROUP BY cr.fullname, cr.id";
$courses = $DB->get_records_sql($sql_2, $placeholders);
}
}
if(!empty($courses)) {
$coursesdata = array();
$currentcourseid = null;
$course = null;
foreach($courses as $completion) {
$context = context_system::instance();
has_capability('moodle/site:config', $context);
if(is_null($currentcourseid) || ($completion->courseid != $currentcourseid)) {
if(!is_null($course)) {
$coursesdata[] = $course;
}
$course = array();
$course['courseid'] = $completion->courseid;
$course['coursename'] = $completion->coursename;
$course['enrols'] = $completion->enrols;
$course['completed'] = $completion->completed;
$course['totalcourses'] = count($course);
}
$currentcourseid = $completion->courseid;
}
if(!is_null($course)){
$coursesdata[] = $course;
}
} else {
$warning = array();
$warning['item'] = 'course';
$warning['itemid'] = $requestedcourseids;
$warning['warningcode'] = '1';
$warning['message'] = 'No course found';
$warnings[] = $warning;
}
$result['course'] = $coursesdata;
$result['warnings'] = $warnings;
return $result;
}
public static function get_completion_overview_returns() {
return new external_single_structure(
array(
'course' => new external_multiple_structure(
new external_single_structure(
array(
'courseid' => new external_value(PARAM_INT, 'description'),
'coursename' => new external_value(PARAM_TEXT, ''),
'enrols' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
'completed' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
'totalcourses' => new external_value(PARAM_INT, '', VALUE_OPTIONAL),
)
)
),
'warnings' => new external_warnings()
)
);
}
}
In your code, the variable $coursesdata is only initialised as an array if at least one requested course is found in the database.
So, the line:
$result['courses'] = $coursesdata;
Will produce a warning message (if debugging is on) and set $result['courses'] to null. The expected type here is an array, so the webservice code correctly complains that the 'courses' value is not the correct type.
To fix, make sure you add:
$coursesdata = [];
Somewhere near the top of your function.
I have a function getCart which has a complicated query that is merged together. I want to select only one array that is $cart['tee_times'] = array(); and place that array in another function. How can I accomplish this?
Here is a snippet of the query I am trying to pull from.
function getCart($id, DBConnection $connection) {
$query = 'SELECT * FROM cart WHERE IDCart=:cart_id LIMIT 1';
$prepared = array(
"cart_id" => $id
);
$results = $connection->fetch($query, $prepared);
$cart = !empty($results) ? $results[0] : null;
if (isset($cart)) {
$cart['IDCustomer'] = isset($cart['IDCustomer']) ? (int)$cart['IDCustomer'] : null;
$cart['IDDestination'] = isset($cart['IDDestination']) ? (int)$cart['IDDestination'] : null;
$cart['total'] = 0;
$cart['tee_times'] = array();
$cart['rooms'] = array();
$cart['cars'] = array();
$query = '
SELECT
a.*,
e. city_name,
f.IDDestination,
((CASE DATE_FORMAT(a.teetime_dt, "%w")
WHEN 0 THEN b.sun
WHEN 1 THEN b.mon
WHEN 2 THEN b.tue
WHEN 3 THEN b.wed
WHEN 4 THEN b.thu
WHEN 5 THEN b.fri
WHEN 6 THEN b.sat
ELSE 0
END) * a.no_rounds * a.no_golfers) price,
c.tax_rate
FROM cart_course_teetimes a
JOIN course_priceplan b
ON b.IDCoursePricePlan = a.IDCoursePricePlan
JOIN course_tax c
ON c.IDCourseTax = a.IDCourseTax
JOIN course d
ON d.IDCourse = b. IDCourse
JOIN vw_cities e
ON e.IDCity = d. IDCity
JOIN destinations_cities f
ON f.IDCity = e.IDCity
WHERE IDCart=:cart_id
';
$results = $connection->fetch($query, $prepared);
foreach ($results as $row) {
$formatted = array(
'IDCartTeetimes' => (int)$row['IDCartTeetimes'],
'IDCoursePricePlan' => (int)$row['IDCoursePricePlan'],
'IDCourseTax' => (int)$row['IDCourseTax'],
'teetime_date' => $row['teetime_dt'],
'num_golfers' => (int)$row['no_golfers'],
'num_rounds' => (int)$row['no_rounds'],
'price' => (float)$row['price'],
'tax_rate' => (float)$row['tax_rate'],
'city_name' => $row['city_name'],
'IDDestination' => (int)$row['IDDestination'],
);
$cart['tee_times'][] = $formatted;
$cart['total'] += $formatted['price'];
}
Here is my function and my attempt at retrieving the tee_times array
function filterCart($cart_id, DBConnection $connection) {
$cart = getCart($cart_id, $connection);
if (!isset($cart)) {
http_response_code(404);
return 'Cart does not exist.';
}
$results =$cart['tee_times'];
echo $results;
$id = null;
foreach ($results as $row){
var_dump($row['IDDestination']);
If you want to filter out courses that have more than one IDDestination, change the WHERE clause to:
WHERE IDCart = :cart_id
AND IDCart NOT IN (
SELECT IDCart
FROM course a
JOIN destinations_cities b ON b.IDCity = a.IDCity
GROUP BY IDCart
HAVING COUNT(*) > 1)
I want to sort highest to lowest cip and also lowest to highest cip, but cip value is not stored in database, it is calculated as soon as query is fired.
Here is html code to select sorting:
<select name="cip">
<option>Select CIP percentage</option>
<option value="1">Highest To Lowest</option>
<option value="2">Lowest To Highest</option>
</select>
And here is the query that I fired!
$select_applicant = "SELECT j.*, u.id, u.gender
FROM job_apply j
LEFT JOIN users u
ON u.id = j.user_id
WHERE j.job_id = '".$jid."'";
$result_applicant = mysqli_query($con, $select_applicant);
while($row_applicant = mysqli_fetch_assoc($result_applicant))
{
$user_id = $row_applicant["user_id"];
$user_info = get_user_profile_info($user_id);
$ratings_dist = get_skill_ratings_stats($user_id);
$got_it_total_rating = 0;
foreach($ratings_dist as $category=>$rating)
{
$got_it_total_rating = $got_it_total_rating + $rating['score'];
}
$got_it_total_category = count($ratings_dist);
$total_cip = ceil($got_it_total_rating / $got_it_total_category);
echo $total_cip;
}
Function "get_skill_ratings_stats" in php is as below:
function get_skill_ratings_stats($user_id){
global $con;
$items = array();
if($user_id>0)
{
$sql = "SELECT
s.category_id category_id,
c.name as category,
COALESCE(r.score_quality, 0.0) quality,
COALESCE(r.score_timing, 0.0) timing,
COALESCE(r.score_budget, 0.0) budget,
COALESCE(r.score_resp, 0.0) resp,
COALESCE(r.score_pro, 0.0) pro
FROM `user_skills` s
LEFT JOIN `skill_categories` c
ON c.category_id=s.category_id
LEFT JOIN `skill_ratings` r
ON r.skill_id=s.skill_id
WHERE s.user_id = '".(int)$user_id."'
AND s.status = 'active'
ORDER BY category ASC";
$prev_cat = '';
$result = mysqli_query($con, $sql);
// die(mysqli_error($con));
while($row = mysqli_fetch_assoc($result))
{
// print_r($row);
if(!$row['category']) continue;
if($row['category']!=$prev_cat)
{
if(isset($items[$prev_cat]['score']) && $items[$prev_cat]['score']>0 && count($items[$prev_cat])>1)
{
$items[$prev_cat]['score'] = floor(($items[$prev_cat]['score']*20)/(count($items[$prev_cat])-1));
}
$prev_cat = $row['category'];
}
if(!isset($items[$prev_cat]['score'])) $items[$prev_cat]['score'] = 0;
$items[$prev_cat][] = $row;
$items[$prev_cat]['score'] += ($row['quality']+$row['timing']+$row['budget']+$row['resp']+$row['pro'])/5;
}
}
// print_r($items);
// die();
if(isset($items[$prev_cat]['score']) && $items[$prev_cat]['score']>0 && count($items[$prev_cat])>1)
{
$items[$prev_cat]['score'] = floor(($items[$prev_cat]['score']*20)/(count($items[$prev_cat])-1));
}
$tmp = array();
foreach($items as $cat=>$item) {
$tmp[$item['score'].'-'.$cat] = $item;
}
krsort($tmp);
$items = array();
foreach($tmp as $k=>$v) {
$k = preg_replace('#^\d+-#is', '', $k);
$items[$k] = $v;
}
// print_r($tmp);
// print_r($items);
// die();
return $items;
}
Please help me! Having hard time with this!
Assuming that you are using a html table to display this I would just go with http://datatables.net/ , it will give you a lot of sorting options very easily...
Otherwise usort():
function cip($a, $b)
{
if ($a['cip'] == $b['cip']) {
return 0;
}
return ($a['cip'] < $b['cip']) ? -1 : 1;
}
$data = array(
[0] => array('cip' => 1)
[1] => array('cip' => 5)
[2] => array('cip' => 2)
);
usort($data, "cip");
foreach ($a as $key => $value) {
echo "$key: $value\n";
}
Assuming your array looks something like this:
array(
[0] => array('cip' => 1)
[1] => array('cip' => 5)
[2] => array('cip' => 2)
)
It basically loops til everything is sorted, all you do in the call back function is tell it which values to compare...
EDIT:
$total_cips[] = array('user_id' => $user_id, 'cip' => ceil($got_it_total_rating / $got_it_total_category));
Ok So now you have all the total cips in an array with there user_id right?
And outside for loop you call usort($total_cips, "cip");
Then you have a sorted array, if you wish to change the sorting direction just change the greater than to a less than in the cip function
as We0 said,
$total_cips[] = array('user_id' => $user_id, 'cip' => ceil($got_it_total_rating / $got_it_total_category));
but then i used multisort function:
function multi_sort($array, $akey)
{
function compare($a, $b)
{
global $key;
return strcmp($a[$key], $b[$key]);
}
usort($array, "compare");
return $array;
}
And then I call the function as below:
$total_cips = multi_sort($total_cips, $key = 'cip');
Finally this one worked!
Anyways thanks We0 & Ankit
Here:
$select_applicant = "SELECT j.*, u.id, u.gender
FROM job_apply j
LEFT JOIN users u
ON u.id = j.user_id
WHERE j.job_id = '".$jid."";
You are missing closing quote for $jid. It should be:
$select_applicant = "SELECT j.*, u.id, u.gender
FROM job_apply j
LEFT JOIN users u
ON u.id = j.user_id
WHERE j.job_id = '".$jid."'";
This might be one of the cause of your problem.