Related
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 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.'\''
I have a problem. I want to json decode the API from https://www.easports.com/fifa/ultimate-team/api/fut/item?page=1, but this only contains 24 players and it has 771(!) pages so that will take forever if you do it one player at one. How can I do it all at once. I currently have this script:
<?php
$conn = mysqli_connect("localhost","u1715p547","L0yRM6pd","u1715p547_ps");
mysqli_set_charset($conn,"utf8");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$page_data_url = "https://www.easports.com/fifa/ultimate-team/api/fut/item?page=1";
// Get the JSON file from EASports
$page_data_plain = file_get_contents($page_data_url);
// Decode the JSON file to a PHP array
$page_data_json = json_decode($page_data_plain, true);
// Get the total pages count
$total_pages_count = $page_data_json['totalPages'];
// Loop through each page
for ($page = 1; $page <= $total_pages_count; $page++){
// Get the EASports JSON per specific page
$item_url = 'https://www.easports.com/fifa/ultimate-team/api/fut/item?page='.$page;
// Get the JSON file from EASports
$item_data_plain = file_get_contents($item_url);
// Decode the JSON file to a PHP array
$item_data_json = json_decode($item_data_plain, true);
// Count the amount of items
$total_items_count = $item_data_json['count'];
// Loop through all items, extract the values and insert in DB
for ($c = 0; $c < $total_items_count; $c++) {
$commonname00 = $item_data_json[$c]['commonName'];
$commonname = str_replace("'", "''", $commonname00);
$firstname00 = $item_data_json[$c]['firstName'];
$firstname = str_replace("'", "''", $firstname00);
$lastname00 = $item_data_json[$c]['lastName'];
$lastname = str_replace("'", "''", $lastname00);
$playerimg = $item_data_json[$c]['headshotImgUrl'];
$leagueid = $item_data_json[$c]['league']['id'];
$nationsmall = $item_data_json[$c]['nation']['imageUrls']['small'];
$nationnormal = $item_data_json[$c]['nation']['imageUrls']['medium'];
$nationlarge = $item_data_json[$c]['nation']['imageUrls']['large'];
$nationid = $item_data_json[$c]['nation']['id'];
$clubsmall = $item_data_json[$c]['club']['imageUrls']['normal']['small'];
$clubnormal = $item_data_json[$c]['club']['imageUrls']['normal']['medium'];
$clublarge = $item_data_json[$c]['club']['imageUrls']['normal']['large'];
$clubid = $item_data_json[$c]['club']['id'];
$largeImgUrl = $item_data_json[$c]['headshot']['largeImgUrl'];
$medImgUrl = $item_data_json[$c]['headshot']['medImgUrl'];
$smallImgUrl = $item_data_json[$c]['headshot']['smallImgUrl'];
$largeSpecImgUrl = $item_data_json[$c]['specialImages']['largeTOTWImgUrl'];
$medSpecImgUrl = $item_data_json[$c]['specialImages']['medTOTWImgUrl'];
$pos = $item_data_json[$c]['position'];
$ps = $item_data_json[$c]['playStyle'];
$heig = $item_data_json[$c]['height'];
$weig = $item_data_json[$c]['weight'];
$bd = $item_data_json[$c]['birthdate'];
$age = $item_data_json[$c]['age'];
$acc = $item_data_json[$c]['acceleration'];
$agg = $item_data_json[$c]['aggression'];
$agi = $item_data_json[$c]['agility'];
$bal = $item_data_json[$c]['balance'];
$ball = $item_data_json[$c]['ballcontrol'];
$foot = $item_data_json[$c]['foot'];
$sm = $item_data_json[$c]['skillMoves'];
$cro = $item_data_json[$c]['crossing'];
$cur = $item_data_json[$c]['curve'];
$dri = $item_data_json[$c]['dribbling'];
$fin = $item_data_json[$c]['finishing'];
$fca = $item_data_json[$c]['freekickaccuracy'];
$gkd = $item_data_json[$c]['gkdiving'];
$gkh = $item_data_json[$c]['gkhandling'];
$gkk = $item_data_json[$c]['gkkicking'];
$gkp = $item_data_json[$c]['gkpositioning'];
$gkr = $item_data_json[$c]['gkreflexes'];
$hea = $item_data_json[$c]['headingaccuracy'];
$int = $item_data_json[$c]['interceptions'];
$jum = $item_data_json[$c]['jumping'];
$lop = $item_data_json[$c]['longpassing'];
$los = $item_data_json[$c]['longshots'];
$mar = $item_data_json[$c]['marking'];
$pen = $item_data_json[$c]['penalties'];
$poi = $item_data_json[$c]['positioning'];
$pot = $item_data_json[$c]['potential'];
$rea = $item_data_json[$c]['reactions'];
$shp = $item_data_json[$c]['shortpassing'];
$sho = $item_data_json[$c]['shotpower'];
$slt = $item_data_json[$c]['slidingtackle'];
$spr = $item_data_json[$c]['sprintspeed'];
$stt = $item_data_json[$c]['standingtackle'];
$sta = $item_data_json[$c]['stamina'];
$str = $item_data_json[$c]['strength'];
$vis = $item_data_json[$c]['vision'];
$vol = $item_data_json[$c]['volleys'];
$wf = $item_data_json[$c]['weakFoot'];
$traits = $item_data_json[$c]['traits'][$c];
$traits1 = $item_data_json[$c]['traits']['1'];
$traits2 = $item_data_json[$c]['traits']['2'];
$traits3 = $item_data_json[$c]['traits']['3'];
$traits4 = $item_data_json[$c]['traits']['4'];
$specialities = $item_data_json[$c]['specialities'][$c];
$specialities1 = $item_data_json[$c]['specialities']['1'];
$specialities2 = $item_data_json[$c]['specialities']['2'];
$specialities3 = $item_data_json[$c]['specialities']['3'];
$specialities4 = $item_data_json[$c]['specialities']['4'];
$specialities5 = $item_data_json[$c]['specialities']['5'];
$specialities6 = $item_data_json[$c]['specialities']['6'];
$specialities7 = $item_data_json[$c]['specialities']['7'];
$specialities8 = $item_data_json[$c]['specialities']['8'];
$specialities9 = $item_data_json[$c]['specialities']['9'];
$specialities10 = $item_data_json[$c]['specialities']['10'];
$atk = $item_data_json[$c]['atkWorkRate'];
$def = $item_data_json[$c]['defWorkRate'];
$pty = $item_data_json[$c]['playerType'];
$pace = $item_data_json[$c]['attributes'][$c]['value'];
$shot = $item_data_json[$c]['attributes']['1']['value'];
$pass = $item_data_json[$c]['attributes']['2']['value'];
$drib = $item_data_json[$c]['attributes']['3']['value'];
$deff = $item_data_json[$c]['attributes']['4']['value'];
$phys = $item_data_json[$c]['attributes']['5']['value'];
$nameof00 = $item_data_json[$c]['name'];
$nameof = str_replace("'", "''", $nameof00);
$qua = $item_data_json[$c]['quality'];
$color = $item_data_json[$c]['color'];
$GK = $item_data_json[$c]['isGK'];
$posfull = $item_data_json[$c]['positionFull'];
$price = $item_data_json[$c]['discardValue'];
$id = $item_data_json[$c]['id'];
$baseId = $item_data_json[$c]['baseId'];
$rating = $item_data_json[$c]['rating'];
$sql = "INSERT IGNORE INTO `players`(`commonName`, `firstName`, `headshotImgUrl`, `lastName`, `leagueid`, `nationimageUrlssmall`, `nationimageUrlsmedium`, `nationimageUrlslarge`, `nationid`, `clubimageUrlsnormalsmall`, `clubimageUrlsnormalmedium`, `clubimageUrlsnormallarge`, `clubid`, `headshotlargeImgUrl`, `headshotmedImgUrl`, `headshotsmallImgUrl`, `specialImageslargeTOTWImgUrl`, `specialImagesmedTOTWImgUrl`, `position`, `playStyle`, `height`, `weight`, `birthdate`, `age`, `acceleration`, `aggression`, `agility`, `balance`, `ballcontrol`, `foot`, `skillMoves`, `crossing`, `curve`, `dribbling`, `finishing`, `freekickaccuracy`, `gkdiving`, `gkhandling`, `gkkicking`, `gkpositioning`, `gkreflexes`, `headingaccuracy`, `interceptions`, `jumping`, `longpassing`, `longshots`, `marking`, `penalties`, `positioning`, `potential`, `reactions`, `shortpassing`, `shotpower`, `slidingtackle`, `sprintspeed`, `standingtackle`, `stamina`, `strength`, `vision`, `volleys`, `weakFoot`, `traits0`, `traits1`, `traits2`, `traits3`, `specialities0`, `specialities1`, `specialities2`, `specialities3`, `specialities4`, `specialities5`, `specialities6`, `specialities7`, `specialities8`, `atkWorkRate`, `defWorkRate`, `playerType`, `attributes0value`, `attributes1value`, `attributes2value`, `attributes3value`, `attributes4value`, `attributes5value`, `name`, `quality`, `color`, `isGK`, `positionFull`, `discardValue`, `id`, `baseId`, `rating`, `specialities9`, `specialities10`, `traits4`)
VALUES ('$commonname', '$firstname', '$playerimg', '$lastname', $leagueid, '$nationsmall', '$nationnormal', '$nationlarge',
$nationid, '$clubsmall', '$clubnormal', '$clublarge', $clubid, '$largeImgUrl', '$medImgUrl',
'$smallImgUrl', '$largeSpecImgUrl', '$medSpecImgUrl', '$pos', '$ps', $heig, $weig, '$bd', $age, $acc, $agg, $agi, $bal, $ball, '$foot', $sm, $cro, $cur, $dri,
$fin, $fca, $gkd, $gkh, $gkk, $gkp, $gkr, $hea, $int, $jum, $lop, $los, $mar, $pen, $poi, $pot, $rea, $shp, $sho, $slt, $spr, $stt, $sta, $str, $vis, $vol, $wf,
'$traits', '$traits1', '$traits2', '$traits3', '$specialities', '$specialities1', '$specialities2', '$specialities3', '$specialities4', '$specialities5',
'$specialities6', '$specialities7', '$specialities8', '$atk', '$def', '$pty', $pace, $shot, $pass, $drib, $deff, $phys, '$nameof', '$qua', '$color', '$GK',
'$posfull', '$price', $id, $baseId, $rating, '$specialities9', '$specialities10', '$traits4')";
echo $sql;
if(!$result = $conn->query($sql))
{
die("<script type='text/javascript'>alert(Fault);</script>");
}
}
}
?>
It just gives me this:
INSERT IGNORE INTO `players`(`commonName`, `firstName`, `headshotImgUrl`, `lastName`, `leagueid`, `nationimageUrlssmall`, `nationimageUrlsmedium`, `nationimageUrlslarge`, `nationid`, `clubimageUrlsnormalsmall`, `clubimageUrlsnormalmedium`, `clubimageUrlsnormallarge`, `clubid`, `headshotlargeImgUrl`, `headshotmedImgUrl`, `headshotsmallImgUrl`, `specialImageslargeTOTWImgUrl`, `specialImagesmedTOTWImgUrl`, `position`, `playStyle`, `height`, `weight`, `birthdate`, `age`, `acceleration`, `aggression`, `agility`, `balance`, `ballcontrol`, `foot`, `skillMoves`, `crossing`, `curve`, `dribbling`, `finishing`, `freekickaccuracy`, `gkdiving`, `gkhandling`, `gkkicking`, `gkpositioning`, `gkreflexes`, `headingaccuracy`, `interceptions`, `jumping`, `longpassing`, `longshots`, `marking`, `penalties`, `positioning`, `potential`, `reactions`, `shortpassing`, `shotpower`, `slidingtackle`, `sprintspeed`, `standingtackle`, `stamina`, `strength`, `vision`, `volleys`, `weakFoot`, `traits0`, `traits1`, `traits2`, `traits3`, `specialities0`, `specialities1`, `specialities2`, `specialities3`, `specialities4`, `specialities5`, `specialities6`, `specialities7`, `specialities8`, `atkWorkRate`, `defWorkRate`, `playerType`, `attributes0value`, `attributes1value`, `attributes2value`, `attributes3value`, `attributes4value`, `attributes5value`, `name`, `quality`, `color`, `isGK`, `positionFull`, `discardValue`, `id`, `baseId`, `rating`, `specialities9`, `specialities10`, `traits4`) VALUES ('', '', '', '', , '', '', '', , '', '', '', , '', '', '', '', '', '', '', , , '', , , , , , , '', , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', , , , , , , '', '', '', '', '', '', , , , '', '', '')
You can't. You have to call it X times where X corresponds to number of pages.
You should ask authors if they could give you entire block of data in single call.
I am trying to generate a PDF dynamically using fpdf, but I am finding it very difficult. Only half of the result I could get. I want to generate my PDF like this:
And now I get a result like this:
Here is the code for PDF:
<?php
require('../fpdf/fpdf.php');
error_reporting(-1);
$id = $_GET['order_id'];
$db = new mysqli('localhost','root','','dbnme'); // use your credentials
class INVPDF extends FPDF
{
var $id;
var $today;
var $widths;
var $heads;
var $aligns;
var $formats;
var $db;
var $invTotal = 0;
var $advancePaid = 0;
//constructor
function INVPDF($invno, $db)
{
parent::fpdf();
$this->id = $invno;
$this->db = $db;
$this->today = date('jS M Y');
$this->heads = array('Item', 'UOM', 'Price', 'Qty', 'Disc %', 'Tax', 'Frt', 'Total' );
$this->widths = array (45, 15, 35, 15, 15, 20, 25, 30);
$this->aligns = array ('L','C','L','C','C','R','C', 'C');
$this->formats = array (0,0,0,0,0,1,0,0);
}
//Page header
function Header()
{
//Arial bold 15
//Title
include("../connect.php");
$ss1 = "select orders.sales_order_id, orders.company_id, lead_address.address, lead_address.address_category, lead_address.country, lead_address.state, lead_address.company_id, lead_address.city,lead_address.pin from orders INNER JOIN lead_address ON orders.company_id=lead_address.company_id where lead_address.address_category='Billing' AND orders.sales_order_id='".$_GET['order_id']."'";
$mq1 = mysql_query($ss1) or die(mysql_error());
$rr1 = mysql_fetch_array($mq1);
$billing = $rr1['address'];
list($line1, $line2, $line3) = explode(',',$billing);
$country = $rr1['country'];
$state = $rr1['state'];
$city = $rr1['city'];
$pin = $rr1['pin'];
//list($line1, $line2, $country, $state, $city, $pin) = explode(',',$address);
$ss2 = "select orders.sales_order_id, orders.company_id, lead_address.address, lead_address.address_category, lead_address.country, lead_address.state, lead_address.company_id, lead_address.city,lead_address.pin from orders INNER JOIN lead_address ON orders.company_id=lead_address.company_id where lead_address.address_category='Shipping' AND orders.sales_order_id='".$_GET['order_id']."'";
$mq2 = mysql_query($ss2) or die(mysql_error());
$rr2 = mysql_fetch_array($mq2);
$shipping = $rr2['address'];
$country1 = $rr2['country'];
$state1 = $rr2['state'];
$city1 = $rr2['city'];
$pin1 = $rr2['pin'];
//$email = $rr1['email'];
// $phone = $rr1['phone'];
// $mobile = $rr1['mobile'];
// $this->SetFont('Arial','B',15);
$this->setXY(10,20);
// $this->Cell(0,10,'INVOICE '.$this->id,0,2,'L');
$this->Image('logo.png',20,6,15);
$this->setXY(12,20);
//
$this->SetFont('OpenSans','',7);
$this->Cell(0,10,'Company Name. ',0,2,'L');
$this->Cell(0,0,'Address1, address2',0,2,'L');
$this->Cell(0,8,'city, stte',0,2,'L');
$this->Cell(0,2,'sales#company.com',0,2,'L');
//$this->Image('images/logo.png',10,6,60);
$this->SetFont('OpenSans','',7);
$this->setXY(12,50);
$this->Cell(0,-2,'Shipping Address',$this->id,0,2,0,'L');
$this->SetFont('OpenSans','',7);
$this->setXY(12,52);
$this ->MultiCell(57,22,'', 'LRTB', 'L', 1);
//$this->Cell(0,8,$name,$this->id,0,2,0,'L');
$this->setXY(12,55);
$this->Cell(0,-1,$shipping,$this->id,0,2,0,'L');
$this->setXY(12,53);
$this->Cell(0,10,$country." , ".$state,$this->id,0,2,0,'L');
$this->setXY(12,52);
$this->Cell(0,20,$city." , ".$pin,$this->id,0,2,0,'L');
$this->SetFont('OpenSans','',7);
$this->setXY(140,52);
$this ->MultiCell(57,22,'', 'LRTB', 'L', 1);
$this->setXY(140,34);
$this->Cell(0,30,'Billing Address',$this->id,0,2,0,'L');
$this->SetFont('OpenSans','',7);
$this->setXY(140,35);
$this->Cell(0,40,$line1." , ".$line2, $this->id,0,2,0,'L');
$this->setXY(140,35);
$this->Cell(0,49,$line3, $this->id,0,2,0,'L');
$this->setXY(140,33);
$this->Cell(0,62,$city1." , ".$pin1,$this->id,0,2,0,'L');
$this->setXY(140,33);
$this->Cell(0,70,$country1." , ".$state1,$this->id,0,2,0,'L');
//$this->setXY(12,65);
// $this->Cell(0,60,$phone,$this->id,0,2,0,'L');
//$this->setXY(12,65);
//$this->Cell(0,70,$mobile,$this->id,0,2,0,'L');
$this->SetFont('OpenSans','',7);
$this->setXY(10,5);
$this->Cell(0,10,'QUOTATION: '.$this->id,0,2,'R');
$this->SetFont('OpenSans','',7);
$until = date ('jS F Y', strtotime($this->today));
$this->Cell(0,0,'Date: '.$until,0,2,'R');
$this->SetFont('OpenSans','',7);
$this->Cell(0,10,'Due Date: Due on receipt',0,2,'R');
//Line break
$this->Ln(60);
for ($i=0; $i<9; $i++)
{
$this->Cell ($this->widths[$i], 8, $this->heads[$i], 1, 0, 'C', 1);
}
$this->Ln(8);
}
//Page footer
function Footer()
{
# $this->SetY(-50); // Uncomment to position at 5 cm from bottom
//Arial italic 8
$this->SetFont('OpenSans','',8);
$w = array_sum(array_slice($this->widths,0,3));
$this->Cell($w,12,'',1);
$this->Cell($this->widths[3],12,'',1,0,'C');
$this->setLeftMargin(45 + array_sum(array_slice($this->widths,0,4)));
$this->Cell($this->widths[5],4,'Sub Total',1);
$this->Cell($this->widths[6],4,number_format($this->invTotal,2),1,0,'R');
$this->Cell($this->widths[7],4,'USD',1,1,'C');
$this->Cell($this->widths[5],4,'Tax',1);
$this->Cell($this->widths[6],4,number_format($this->advancePaid,2),1,0,'R');
$this->Cell($this->widths[7],4,'USD',1,1,'C');
$this->Cell($this->widths[5],4,'Freight',1);
$this->Cell($this->widths[6],4,number_format($this->freight,2),1,0,'R');
$this->Cell($this->widths[7],4,'USD',1,1,'C');
$this->setLeftMargin(10);
$this->Cell($this->widths[5],4,'Total',1);
$this->Cell($this->widths[6],4,number_format($this->invTotal+$this->advancePaid,2),1,0,'R');
$this->Cell($this->widths[7],4,'USD',1,1,'C');
$this->SetFont('OpenSans','',6);
$this->Cell($w,10,'',0,0,'L');
$this->Cell(30,4,'Private Limited Company - TIN: 345sddd - PAN: sf43534',0,0,'C');
//$this->Cell($w,10,'');
$this->Cell(-30,12,'SRVC TAX: gddddddddddd - CIN: sdgdgdgdfgfdgfg',0,0,'C');
$this->Cell(30,20,'This document has been electronically generated and requires no physical signature or stamp.',0,0,'C');
}
function makeInvoice()
{
$sql = "select before_order_line_items.item, before_order_line_items.description, before_order_line_items.uom, before_order_line_items.selling_price, before_order_line_items.quantity, before_order_line_items.discount, before_order_line_items.tax, before_order_line_items.freight, before_order_line_items.tax_amount, before_order_line_items.total, items.name as iname, taxes.tax_id, taxes.name as tname, taxes.rate from before_order_line_items inner join items on before_order_line_items.item=items.item_id inner join taxes on before_order_line_items.tax=taxes.tax_id where before_order_line_items.sales_order_id = '".$_GET['order_id']."' ";
//echo $sql;
$res = $this->db->query($sql) or die($this->db->error);
$this->SetFont('OpenSans','',8);
if ($res->num_rows > 0)
{
while ($r = $res->fetch_row())
{
$this->invTotal += $r[10];
foreach ($r as $c => $value) {
//echo $value;
if ($this->formats[$c]) {
$value = number_format($value);
// echo $value;
}
$this->Cell($this->widths[$c],10,$value,'LR',0, $this->aligns[$c]);
}
$this->Ln();
//$amount = number_format($amount+$value);
}
}
}
} # invpdf class
$invno = $_GET['order_id'];
//Instantiation of inherited class
$pdf = new INVPDF($invno, $db);
$pdf->Open();
$pdf->AliasNbPages();
$pdf->setLeftMargin(10);
$pdf->setRightMargin(10);
$pdf->AddFont('OpenSans','','Opensans-Regular.php');
$pdf->SetFont('OpenSans','',7);
$pdf->SetDrawColor(102);
$pdf->SetFillColor(220);
$pdf->AddPage();
$pdf->makeInvoice();
$pdf->Output();
?>
Can somebody please help me how to do it? or is there any example code for something similar to this?
Looking at your actual pdf and expected pdf.. you are missing the no. column in table header.
This line-
$this->heads = array('Item', 'UOM', 'Price', 'Qty', 'Disc %', 'Tax', 'Frt', 'Total' );
should be-
$this->heads = array('No.', 'Item', 'UOM', 'Price', 'Qty', 'Disc %', 'Tax', 'Frt', 'Total' );