How to unenroll user from a course with php - php

Using Moodle 1.9, I have successfully been able to enroll a user via php with
$user = get_record("user", "id", $mqval['id']);
$course = get_record("course", "id", $cid);
if ( ! enrol_into_course($course, $user, 'manuel')) {
} else {
//echo 'success';
}
Now I want to unenroll the user the same way. I tried using unenrol_user, which didn't work. I also tried role_unassign but with no success.

//get instance that can unenrol
$enrols = enrol_get_plugins(true);
$enrolinstances = enrol_get_instances($courseid, true);
$unenrolled = false;
foreach ($enrolinstances as $instance) {
if (!$unenrolled and $enrols[$instance->enrol]->allow_unenrol($instance)) {
$unenrolinstance = $instance;
$unenrolled = true;
}
}
//unenrol the user in every course he's in
$enrolledusercourses = enrol_get_users_courses($userid);
foreach ($enrolledcourses as $course) {
//unenrol the user
$enrols[$unenrolinstance->enrol]->unenrol_user($unenrolinstance, $userid, $roleid);
}

I have modified above code and its working.
//unenrol the user in every course he's in
$enrols = enrol_get_plugins(true);
$enrolledusercourses = enrol_get_users_courses($user->id);
foreach ($enrolledusercourses as $course) {
//unenrol the user
$courseid = $course->id;
$enrolinstances = enrol_get_instances($courseid, true);
$unenrolled = false;
foreach ($enrolinstances as $instance) {
if (!$unenrolled and $enrols[$instance->enrol]->allow_unenrol($instance)) {
$unenrolinstance = $instance;
$unenrolled = true;
}
}
$enrols[$unenrolinstance->enrol]->unenrol_user($unenrolinstance, $user->id, $user->rollid);
}

Related

Is it possible to update inventory_policy for all products using API in Shopify?

From my PHP application, I want to update the inventory_policy (continue/deny) of all products using API. Is there any way to do so without a loop?
I did not find any way to update it at once. Hence, I have updated it one by one. Please have the code below.
public function update_inventory_policy_for_all_item($inventory_policy, $page_info=null){
$response = $this->do_get("/admin/api/2021-04/products.json?limit=250".$page_info);
if ($response === FALSE)
{
return false;
}
$result_products = $response['body']['products'];
$headers = $response['headers'];
foreach($result_products as $shopify_product){
foreach($shopify_product['variants'] as $variant){
$variant_id = $variant['id'];
$data['variant'] = array(
'id' => $variant['id'],
'inventory_policy' => $inventory_policy,
);
$this->do_put("/admin/api/2021-04/variants/$variant_id.json", $data);
}
}
if(isset($headers['link'])) {
$links = explode(',', $headers['link']);
foreach($links as $link) {
$next_page = false;
if(strpos($link, 'rel="next"')) {
$next_page = $link;
}
}
if($next_page) {
preg_match('~<(.*?)>~', $next_page, $next);
$url_components = parse_url($next[1]);
parse_str($url_components['query'], $params);
$page_info = '&page_info=' . $params['page_info'];
$this->update_inventory_policy_for_all_item($inventory_policy, $page_info);
}
}
return true;
}

Can I edit the Amelia wordpress booking system to create a new customer without booking?

need my customers to be able to log into the site with the same details as they book with, as i can make a customer in amelia that adds itself to the default wordpress user list but when i make a wordpress user with the amelia customer role it does not transfer over across to amelia.
not a clue if this helps but found this in the plugin php.
<?php
namespace AmeliaBooking\Domain\Factory\User;
use AmeliaBooking\Domain\Common\Exceptions\InvalidArgumentException;
use AmeliaBooking\Domain\Entity\User\Customer;
use AmeliaBooking\Domain\Entity\User\Manager;
use AmeliaBooking\Domain\Entity\User\Admin;
use AmeliaBooking\Domain\Entity\User\Provider;
use AmeliaBooking\Domain\Factory\Bookable\Service\ServiceFactory;
use AmeliaBooking\Domain\Factory\Google\GoogleCalendarFactory;
use AmeliaBooking\Domain\Factory\Outlook\OutlookCalendarFactory;
use AmeliaBooking\Domain\Factory\Schedule\PeriodServiceFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodFactory;
use AmeliaBooking\Domain\Factory\Schedule\SpecialDayPeriodServiceFactory;
use AmeliaBooking\Domain\ValueObjects\DateTime\Birthday;
use AmeliaBooking\Domain\ValueObjects\Gender;
use AmeliaBooking\Domain\ValueObjects\Json;
use AmeliaBooking\Domain\ValueObjects\String\Password;
use AmeliaBooking\Domain\ValueObjects\String\Status;
use AmeliaBooking\Domain\ValueObjects\Picture;
use AmeliaBooking\Domain\ValueObjects\String\Description;
use AmeliaBooking\Domain\ValueObjects\String\Email;
use AmeliaBooking\Domain\ValueObjects\Number\Integer\Id;
use AmeliaBooking\Domain\ValueObjects\String\Name;
use AmeliaBooking\Domain\ValueObjects\String\Phone;
use AmeliaBooking\Domain\Collection\Collection;
use AmeliaBooking\Domain\Factory\Schedule\DayOffFactory;
use AmeliaBooking\Domain\Factory\Schedule\TimeOutFactory;
use AmeliaBooking\Domain\Factory\Schedule\PeriodFactory;
use AmeliaBooking\Domain\Factory\Schedule\WeekDayFactory;
/**
* Class UserFactory
*
* #package AmeliaBooking\Domain\Factory\User
*/
class UserFactory
{
/**
* #param $data
*
* #return Admin|Customer|Manager|Provider
* #throws InvalidArgumentException
*/
public static function create($data)
{
if (!isset($data['type'])) {
$data['type'] = 'customer';
}
switch ($data['type']) {
case 'admin':
$user = new Admin(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'])
);
break;
case 'provider':
$weekDayList = [];
$dayOffList = [];
$specialDayList = [];
$serviceList = [];
$appointmentList = [];
if (isset($data['weekDayList'])) {
foreach ((array)$data['weekDayList'] as $weekDay) {
$timeOutList = [];
if (isset($weekDay['timeOutList'])) {
foreach ((array)$weekDay['timeOutList'] as $timeOut) {
$timeOutList[] = TimeOutFactory::create($timeOut);
}
$weekDay['timeOutList'] = $timeOutList;
}
$periodList = [];
if (isset($weekDay['periodList'])) {
foreach ((array)$weekDay['periodList'] as $period) {
$periodServiceList = [];
if (isset($period['periodServiceList'])) {
foreach ((array)$period['periodServiceList'] as $periodService) {
$periodServiceList[] = PeriodServiceFactory::create($periodService);
}
}
$period['periodServiceList'] = $periodServiceList;
$periodList[] = PeriodFactory::create($period);
}
$weekDay['periodList'] = $periodList;
}
$weekDayList[] = WeekDayFactory::create($weekDay);
}
}
if (isset($data['specialDayList'])) {
foreach ((array)$data['specialDayList'] as $specialDay) {
$periodList = [];
if (isset($specialDay['periodList'])) {
foreach ((array)$specialDay['periodList'] as $period) {
$periodServiceList = [];
if (isset($period['periodServiceList'])) {
foreach ((array)$period['periodServiceList'] as $periodService) {
$periodServiceList[] = SpecialDayPeriodServiceFactory::create($periodService);
}
}
$period['periodServiceList'] = $periodServiceList;
$periodList[] = SpecialDayPeriodFactory::create($period);
}
$specialDay['periodList'] = $periodList;
}
$specialDayList[] = SpecialDayFactory::create($specialDay);
}
}
if (isset($data['dayOffList'])) {
foreach ((array)$data['dayOffList'] as $dayOff) {
$dayOffList[] = DayOffFactory::create($dayOff);
}
}
if (isset($data['serviceList'])) {
foreach ((array)$data['serviceList'] as $service) {
$serviceList[$service['id']] = ServiceFactory::create($service);
}
}
$user = new Provider(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email']),
new Phone(isset($data['phone']) ? $data['phone'] : null),
new Collection($weekDayList),
new Collection($serviceList),
new Collection($dayOffList),
new Collection($specialDayList),
new Collection($appointmentList)
);
if (!empty($data['password'])) {
$user->setPassword(new Password($data['password']));
}
if (!empty($data['locationId'])) {
$user->setLocationId(new Id($data['locationId']));
}
if (!empty($data['googleCalendar']) && isset($data['googleCalendar']['token'])) {
$user->setGoogleCalendar(GoogleCalendarFactory::create($data['googleCalendar']));
}
if (!empty($data['outlookCalendar']) && isset($data['outlookCalendar']['token'])) {
$user->setOutlookCalendar(OutlookCalendarFactory::create($data['outlookCalendar']));
}
if (!empty($data['zoomUserId'])) {
$user->setZoomUserId(new Name($data['zoomUserId']));
}
if (!empty($data['id'])) {
$user->setId(new Id($data['id']));
}
break;
case 'manager':
$user = new Manager(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'])
);
break;
case 'customer':
default:
$user = new Customer(
new Name($data['firstName']),
new Name($data['lastName']),
new Email($data['email'] ?: null),
new Phone(!empty($data['phone']) ? $data['phone'] : null),
new Gender(!empty($data['gender']) ? strtolower($data['gender']) : null)
);
break;
}
if (!empty($data['countryPhoneIso'])) {
$user->setCountryPhoneIso(new Name($data['countryPhoneIso']));
}
if (!empty($data['birthday'])) {
if (is_string($data['birthday'])) {
$user->setBirthday(new Birthday(\DateTime::createFromFormat('Y-m-d', $data['birthday'])));
} else {
$user->setBirthday(new Birthday($data['birthday']));
}
}
if (!empty($data['id'])) {
$user->setId(new Id($data['id']));
}
if (!empty($data['externalId'])) {
$user->setExternalId(new Id($data['externalId']));
}
if (!empty($data['pictureFullPath']) && !empty($data['pictureThumbPath'])) {
$user->setPicture(new Picture($data['pictureFullPath'], $data['pictureThumbPath']));
}
if (!empty($data['status'])) {
$user->setStatus(new Status($data['status']));
}
if (!empty($data['note'])) {
$user->setNote(new Description($data['note']));
}
return $user;
}
}
Try this. Found it on the support forums.
add_action( 'user_register', 'custom_amelia_registration_save', 10, 1 );
function custom_amelia_registration_save($user_id) {
global $wpdb;
$wpUser = get_user_by('ID', $user_id);
$ameliaUserId = $wpdb->get_col(
"SELECT id FROM wp_amelia_users WHERE email = '{$wpUser->user_email}'"
);
if (!$ameliaUserId && in_array('wpamelia-customer', $wpUser->roles)) {
$ameliaUserFirstName = $wpUser->user_first_name ?: $wpUser->user_nicename;
$ameliaUserLastName = $wpUser->user_last_name ?: $wpUser->user_nicename;
$wpdb->query("
INSERT INTO wp_amelia_users
(
type,
status,
externalId,
firstName,
lastName,
email
) VALUES (
'customer',
'visible',
{$user_id},
'{$ameliaUserFirstName}',
'{$ameliaUserLastName}',
'{$wpUser->user_email}'
)
");
}
}

How do I modify an existing file to add the ability to unlink a specific file from a folder?

Thank you StackOverflow experts for looking at my question.
First, It is possible this question has been asked before but my situation is a bit unique. So, please hear me out.
When our users want to edit an existing record, they would also like to have the ability to delete an existing pdf file if one exists before adding a new one.
To display an existing file, I use this code.
<td class="td_input_form">
<?php
// if the BidIDFile is empty,
if(empty($result["BidIDFile"]))
{
//then show file upload field for Bid File
echo '<input type="file" name="BidIDFile[]" size="50">';
}
else
{
// Bid file already upload, show checkbox to delete it.
echo '<input type="checkbox" name="delete[]" value="'.$result["BidIDFile"].'"> (delete)
'.$result["BidIDFile"].'';
}
</td>
Then to delete this file, I use the following code:
// Connect to SQL Server database
include("connections/Connect.php");
// Connect to SQL Server database
include("connections/Connect.php");
$strsID = isset($_GET["Id"]) ? $_GET["Id"] : null;
if(isset($_POST['delete']))
{
// whilelisted table columns
$fileColumnsInTable = array( 'BidIDFile', 'TabSheet', 'SignInSheet', 'XConnect',
'Addend1', 'Addend2','Addend3','Addend4','Addend5', 'Addend6');
$fileColumns = array();
foreach ($_POST['delete'] as $fileColumn)
{
if(in_array($fileColumn, $fileColumnsInTable))
$fileColumns[] = $fileColumn;
}
// get the file paths for each file to be deleted
$stmts = "SELECT " . implode(', ', $fileColumns) . " FROM bids WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
$files = sqlsrv_fetch_array($querys,SQLSRV_FETCH_ROW);
// loop over the files returned by the query
foreach ($files as $file )
{
//delete file
unlink($file);
}
// now remove the values from the table
$stmts = "UPDATE bids SET " . impload(' = '', ', $fields) . " WHERE ID = ? ";
$querys = sqlsrv_query( $conn, $stmts, array($strsID));
This works fine. However, the edit file points to an existing file with an INSERT and UPDATE operation in this one file (great thanks to rasclatt) and I am having problem integrating the two together.
Can someone please help with integrating the two files into one?
Thanks in advance for your assistance.
Here is the INSERT and UPDATE file:
<?php
error_reporting(E_ALL);
class ProcessBid
{
public $data;
public $statement;
public $where_vals;
protected $keyname;
protected $conn;
public function __construct($conn = false)
{
$this->conn = $conn;
}
public function SaveData($request = array(),$skip = false,$keyname = 'post')
{
$this->keyname = $keyname;
$this->data[$this->keyname] = $this->FilterRequest($request,$skip);
return $this;
}
public function FilterRequest($request = array(), $skip = false)
{
// See how many post variables are being sent
if(count($request) > 0) {
// Loop through post
foreach($request as $key => $value) {
// Use the skip
if($skip == false || (is_array($skip) && !in_array($key,$skip))) {
// Create insert values
$vals['vals'][] = "'".ms_escape_string($value)."'";
// Create insert columns
$vals['cols'][] = "".str_replace("txt","",$key)."";
// For good measure, create an update string
$vals['update'][] = "".str_replace("txt","",$key)."".' = '."'".ms_escape_string($value)."'";
// For modern day binding, you can use this array
$vals['bind']['cols'][] = "".$key."";
$vals['bind']['cols_bind'][] = ":".$key;
$vals['bind']['vals'][":".$key] = $value;
$vals['bind']['update'][] = "".$key.' = :'.$key;
}
}
}
return (isset($vals))? $vals:false;
}
public function AddFiles($name = 'item')
{
// If the files array has been set
if(isset($_FILES[$name]['name']) && !empty($_FILES[$name]['name'])) {
// Remove empties
$_FILES[$name]['name'] = array_filter($_FILES[$name]['name']);
$_FILES[$name]['type'] = array_filter($_FILES[$name]['type']);
$_FILES[$name]['size'] = array_filter($_FILES[$name]['size']);
$_FILES[$name]['tmp_name'] = array_filter($_FILES[$name]['tmp_name']);
// we need to differentiate our type array names
$use_name = ($name == 'item')? 'Addend':$name;
// To start at Addendum1, create an $a value of 1
$a = 1;
if(!empty($_FILES[$name]['tmp_name'])) {
foreach($_FILES[$name]['name'] as $i => $value ) {
$file_name = ms_escape_string($_FILES[$name]['name'][$i]);
$file_size = $_FILES[$name]['size'][$i];
$file_tmp = $_FILES[$name]['tmp_name'][$i];
$file_type = $_FILES[$name]['type'][$i];
if(move_uploaded_file($_FILES[$name]['tmp_name'][$i], $this->target.$file_name)) {
// Format the key values for addendum
if($name == 'item')
$arr[$use_name.$a] = $file_name;
// Format the key values for others
else
$arr[$use_name] = $file_name;
$sql = $this->FilterRequest($arr);
// Auto increment the $a value
$a++;
}
}
}
}
if(isset($sql) && (isset($i) && $i == (count($_FILES[$name]['tmp_name'])-1)))
$this->data[$name] = $sql;
return $this;
}
public function SaveFolder($target = '../uploads/')
{
$this->target = $target;
// Makes the folder if not already made.
if(!is_dir($this->target))
mkdir($this->target,0755,true);
return $this;
}
public function where($array = array())
{
$this->where_vals = NULL;
if(is_array($array) && !empty($array)) {
foreach($array as $key => $value) {
$this->where_vals[] = $key." = '".ms_escape_string($value)."'";
}
}
return $this;
}
public function UpdateQuery()
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$update[] = implode(",",$arr['update']);
}
}
$vars = (isset($update) && is_array($update))? implode(",",$update):"";
// Check that both columns and values are set
$this->statement = (isset($update) && !empty($update))? "update bids set ".implode(",",$update):false;
if(isset($this->where_vals) && !empty($this->where_vals)) {
$this->statement .= " where ".implode(" and ",$this->where_vals);
}
return $this;
}
public function SelectQuery($select = "*",$table = 'bids')
{
$stmt = (is_array($select) && !empty($select))? implode(",",$select):$select;
$this->statement = "select ".$stmt." from ".$table;
return $this;
}
public function InsertQuery($table = 'bids')
{
$this->data = array_filter($this->data);
if(empty($this->data)) {
$this->statement = false;
return $this;
}
$this->statement = "insert into ".$table;
if(isset($this->data) && !empty($this->data)) {
foreach($this->data as $name => $arr) {
$insert['cols'][] = implode(",",$arr['cols']);
$insert['vals'][] = implode(",",$arr['vals']);
}
}
$this->statement .= '(';
$this->statement .= (isset($insert['cols']) && is_array($insert['cols']))? implode(",",$insert['cols']):"";
$this->statement .= ") VALUES (";
$this->statement .= (isset($insert['vals']) && is_array($insert['vals']))? implode(",",$insert['vals']):"";
$this->statement .= ")";
return $this;
}
}
include("../Connections/Connect.php");
function render_error($settings = array("title"=>"Failed","body"=>"Sorry, your submission failed. Please go back and fill out all required information."))
{ ?>
<h2><?php echo (isset($settings['title']))? $settings['title']:"Error"; ?></h2>
<p><?php echo (isset($settings['body']))? $settings['body']:"An unknown error occurred."; ?></p>
<?php
}
// this function is used to sanitize code against sql injection attack.
function ms_escape_string($data)
{
if(!isset($data) || empty($data))
return "";
if(is_numeric($data))
return $data;
$non_displayables[] = '/%0[0-8bcef]/'; // url encoded 00-08, 11, 12, 14, 15
$non_displayables[] = '/%1[0-9a-f]/'; // url encoded 16-31
$non_displayables[] = '/[\x00-\x08]/'; // 00-08
$non_displayables[] = '/\x0b/'; // 11
$non_displayables[] = '/\x0c/'; // 12
$non_displayables[] = '/[\x0e-\x1f]/'; // 14-31
foreach($non_displayables as $regex)
$data = preg_replace($regex,'',$data);
$data = str_replace("'","''",$data);
return $data;
}
// New bid save engine is required for both sql statement generations
$BidSet = new ProcessBid($conn);
$strId = null;
if(isset($_POST["Id"]))
{
$strId = $_POST["Id"];
//echo $strId;
}
If ($strId == "") {
//echo "This is an insert statement";
// This will generate an insert query
$insert = $BidSet->SaveData($_POST)
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->InsertQuery()
->statement;
// Check that statement is not empty
if($insert != false) {
sqlsrv_query($conn,$insert);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to Solicitation screen'));
$err = false;
}
//echo '<pre>';
//print_r($insert);
// echo '</pre>';
}
else
{
//echo "This is an update statement";
// This will generate an update query
$update = $BidSet->SaveData($_POST,array("Id"))
->SaveFolder('../uploads/')
->AddFiles('BidIDFile')
->AddFiles('item')
->AddFiles('SignInSheet')
->AddFiles('TabSheet')
->AddFiles('Xcontract')
->where(array("Id"=>$_POST["Id"]))
->UpdateQuery()
->statement;
//echo '<pre>';
//print_r($update);
//echo '</pre>';
// Check that statement is not empty
if($update != false) {
sqlsrv_query($conn,$update);
render_error(array("title"=>"Bid Successfully Saved!","body"=>'Go back to admin screen'));
$err = false;
}
}
// This will post an error if the query fails
if((isset($err) && $err == true) || !isset($err))
render_error(); ?>

Moodle php - where does moodle check if the provided enrolment key matches the course's predefined enrollment key?

I am creating a moodle website. I already setup my courses with their specific enrolment keys, etc. But I want to know in what .php file and where in that file (in the moodle files), does Moodle check if the enrollment key entered by the user matches what I set as the enrolment key for the course...
Thanks for your help!
UPDATE--------
I did as Russell England suggested, but when I go to the page where I type my enrolment key, the page isn't loading or the page is redirected to my moodle homepage. My table that I store the enrolment keys is user_enrolment_keys.
Here is the updated validation function:
public function validation($data, $files) {
global $DB, $CFG, $USER;
$errors = parent::validation($data, $files);
$instance = $this->instance;
if ($this->toomany) {
$errors['notice'] = get_string('error');
return $errors;
}
//--------Russell's suggestion--------------
if ($instance->password) {
$params = array('user_email' => $USER->email, 'course_id' => $instance->courseid, 'enrolment_key' => $data['enrolpassword']);
if (!$DB->record_exists('user_enrolment_keys', $params)) {
$errors['enrolpassword'] = get_string('passwordinvalid', 'enrol_self');
return $errors;
}
}
//What I tried last (did not work either)...
/*$uemail = $USER->email;
$userscoursekey = 'testing';
$connecty = mysqli_connect("localhost", "...", "...", "...");
mysql_select_db('user_enrolment_keys', $connecty);
$var2 = $instance->courseid;
$resulty = mysqli_query($connecty, "SELECT * FROM user_enrolment_keys WHERE user_email='$uemail' AND course_id='$var2'");
$numrows = $resulty->num_rows;
if($numrows > 0)
{
while($row = mysqli_fetch_assoc($resulty))
{
$userscoursekey = $row['enrolment_key'];
}
}
$instance->password = $userscoursekey;
my_sqli_close($connecty); //Close the database connection.*/
if ($instance->password) {
if ($data['enrolpassword'] !== $instance->password) {
if ($instance->customint1) {
$groups = $DB->get_records('groups', array('courseid'=>$instance->courseid), 'id ASC', 'id, enrolmentkey');
$found = false;
foreach ($groups as $group) {
if (empty($group->enrolmentkey)) {
continue;
}
if ($group->enrolmentkey === $data['enrolpassword']) {
$found = true;
break;
}
}
if (!$found) {
// We can not hint because there are probably multiple passwords.
$errors['enrolpassword'] = get_string('passwordinvalid', 'enrol_self');
}
} else {
$plugin = enrol_get_plugin('self');
if ($plugin->get_config('showhint')) {
$hint = core_text::substr($instance->password, 0, 1);
$errors['enrolpassword'] = get_string('passwordinvalidhint', 'enrol_self', $hint);
} else {
$errors['enrolpassword'] = get_string('passwordinvalid', 'enrol_self');
}
}
}
}
return $errors;
// END DEFAULT BLOCK
}
Its validated in the custom self enrolment form
In the function validation() in the file /enrol/self/locallib.php it checks if the password matches and displays an error if not.
UPDATE:
I would probably do this in the validation function
Add the $USER variable at the top
global $DB, $CFG, $USER;
Then check if the user, course and password combination exists in your newly created licence table ;)
$params = array('userid' => $USER->id, 'courseid' => $instance->courseid, 'password' => $data['enrolpassword']);
if (!$DB->record_exists('local_licence_table', $params)) {
$errors['enrolpassword'] = get_string('passwordinvalid', 'enrol_self');
return $errors;
}

Return in foreach showing only 1st value

I have problem. In my function, return shows only first player from server. I wanted to show all players from server, but i cant get this working. Here is my code:
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
return '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
}
}
}
You're returning from within your loop.
Instead, you should concatenate the results for each iteration and then return that concatenated string outside the loop.
e.g.
$result = "";
foreach($aPlayers as $sValue) {
# add to $result...
}
return $result
function players() {
require_once "inc/SampQueryAPI.php";
$query = new SampQueryAPI('uh1.ownserv.pl', 25052); // Zmień dane obok! //
if($query->isOnline())
{
$aInformation = $query->getInfo();
$aServerRules = $query->getRules();
$aPlayers = $query->getDetailedPlayers();
if(!is_array($aPlayers) || count($aPlayers) == 0)
{
return 'Brak graczy online';
}
else
{
$ret = '';
foreach($aPlayers as $sValue)
{
$playerid = $sValue['playerid'];
$playername = htmlentities($sValue['nickname']);
$playerscore = $sValue['score'];
$playerping = $sValue['ping'];
$ret .= '<li>'.$playername.' (ID: '.$playerid.'), Punkty ('.$playerscore.'), Ping ('.$playerping.')</li>';
}
return $ret;
}
}
}
In a function you can only return ONE value.
Try creating a list of players and return the list when all records have been added to it.
In your case, list of players will result in an array of players

Categories