I am programming a Module for Contao in php.
I am using the function "Model::save()", which saves my data to the database.
But when I am trying to use the model after saving, it's just empty. I have no idea how this can happen.
The Code Snippet:
$report->tstamp = time();
$report->machine_id = $machine_data['type_of_machine'];
var_dump($report);
echo "<br/>";
$report->save();
var_dump($report);
echo "<br/>";
So in the var_dump before I save, everything is fine, but the second one doesn't show any data!
Does anybody got some ideas?
Edit2:
OK, here the complete code of the Module:
<?php
use Contao\Date;
use Contao\FilesModel;
use Contao\Input;
use Contao\Module;
use Contao\PageModel;
use Contao\RequestToken;
use Contao\Validator;
class ModuleReportData extends Module
{
protected $strTemplate = 'mod__reportdata';
public function generate()
{
if (TL_MODE == 'BE')
{
/** #var \BackendTemplate|object $objTemplate */
$objTemplate = new \BackendTemplate('be_wildcard');
$objTemplate->wildcard = '### ReportData ###';
$objTemplate->href = 'contao/main.php?do=themes&table=tl_module&act=edit&id=' . $this->id;
return $objTemplate->parse();
}
return parent::generate();
}
public function compile()
{
$report_id = Input::get('r');
if($report_id){
$report = ReportModel::findByPk($report_id);
$project = ProjectModel::findBy('report_id', $report_id);
}else{
$report = new ReportModel();
$project = new ProjectModel();
}
$machine = new MachineModel();
$machines = [];
$next_step = false;
//get data for selectbox machines
$result = $this->Database->prepare("SELECT * FROM tl_sa_machines")->execute();
while($result->next())
{
$id = $result->id;
$machines[$id] = $result->type;
}
//Check if form was submitted
if(Input::post('submit_data')){
$report_data = Input::post('report_data');
$project_data = Input::post('project_data');
$machine_data = Input::post('machine_data');
$errors = [];
$next_step = true;
foreach($report_data as $key => $data)
{
if(empty($data)) continue;
switch ($key) {
case 'document_date':
if (preg_match("/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/", $data)) //###andere Formate hinzufügen
{
break;
}
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'customer':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'city':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'country':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'document_version':
if(Validator::isNumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'author':
if(Validator::isAlphanumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
case 'max_speed':
if(Validator::isNumeric($data)) break;
else {
$next_step = false;
$errors[$key] ="Error";
break;
}
}
}
$report->setRow($report_data);
foreach($project_data as $key => $data)
{
if(empty($data)) continue;
if(Validator::isAlphanumeric($data)) continue;
else {
$next_step = false;
$errors[$key] = "Error";
}
}
$project->setRow($project_data);
if($next_step)
{
$project->date_of_evaluation = strtotime($project->date_of_evaluation);
$report->document_date = strtotime($report->document_date);
//save and set report_data
$report->tstamp = time();
$report->machine_id = $machine_data['type_of_machine'];
var_dump($report);
echo "<br/>";
$report->save();
var_dump($report);
echo "<br/>";
$report = ReportModel::findByPK($report_id);
var_dump($report);
//save and set project_data
$project->report_id = $report->id;
$project->tstamp = time();
$project->save();
//session for transfering report_id to the next page
/* var_dump($report->id);
var_dump($report_id);
var_dump($project->report_id);
if($report_id) {
$_SESSION['report_id'] = $report_id;
}
else
{//var_dump($report_id);
//var_dump($report->id);
$report_id = $report->id;
$_SESSION['report_id'] = $report_id;
}
$jumpTo = PageModel::findByPk($this->jumpTo);
$url = $this->generateFrontendUrl($jumpTo->row());
$this->redirect($url);*/
}
}
$this->Template->report = $report;
$this->Template->project = $project;
$this->Template->machine = $machine;
$this->Template->machines = $machines;
$this->Template->errors = $errors;
$this->Template->request_token = RequestToken::get();
}
}
I have a form, to save new data, or to edit existing data. There are two different tables in the database I am trying to fill with data. FOr second one I need the new ID of the new row generated in this code. But it doesn't work because the model is empty after saving.
Edit3:
ProjectModel is just that simple:
use Contao\Model;
class ProjectModel extends Model{
protected static $strTable = "tl_sa_projects";
}
I just found out, it only happens when I use the save method on $report. It's working fine with $project!
Update:
It looks like I get an error when the refresh() method tries to select the new inserted databaserow with:
public function refresh()
{
$intPk = $this->{static::$strPk};
// Track primary key changes
if (isset($this->arrModified[static::$strPk]))
{
$intPk = $this->arrModified[static::$strPk];
}
// Reload the database record
$res = \Database::getInstance()->prepare("SELECT * FROM " . static::$strTable . " WHERE " . static::$strPk . "=?")
->execute($intPk);
var_dump($res);
$this->setRow($res->row());
}
Update 2:
Ok the problem is, that the "arrModified" contains an empty string as ID. Does anybody know where this array gets its elements?
Not the answer to your original question, but you should use
ProjectModel::findOneBy('report_id', $report_id);
instead of
ProjectModel::findBy('report_id', $report_id);
since you want to find only one specific project. findBy returns a Contao\Model\Collection (i.e. potentially multiple results) whereas findOneBy returns a Contao\Model.
Update:
Furthermore, your usage of setData and mergeRow is probably not intended this way. You should instead use
foreach ($project_data as $key => $val)
{
$project->$key = $val;
}
for instance.
Related
I have some sample code within a controller method that looks up a cookie and manipulates the model if it exists, or creates a new model and returns a new cookie if it doesn't.
Is it possible to add the cookie before I return the view such that the duplicated code can be written only once?
I'm just looking for efficiency and tidiness.
$cat = Cat::find($request->cookie('cat_id'));
if (null !== $cat) {
if ($cat->name === 'Felix') {
$cat->age = 10;
} else {
$cat->age = 8;
}
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
return redirect('/');
} else {
$cat = new Cat;
$cat->name = 'Ralf';
$cat->age = 12;
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
return redirect('/')->withCookie(cookie('cat_id', $cat->id,10000));
}
The redirect() method returns a Illuminate\Http\RedirectResponse when a string is passed to it, which the Laravel routing stack interprets as a direction to send out a particular response header. So instead of returning twice, you can just do this:
$cat = Cat::find($request->cookie('cat_id'));
$redirect = redirect('/');
if (null !== $cat) {
if ($cat->name === 'Felix') {
$cat->age = 10;
} else {
$cat->age = 8;
}
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
} else {
$cat = new Cat;
$cat->name = 'Ralf';
$cat->age = 12;
//duplicated code
$cat->fur = 'soft';
$cat->tail = 'wavy';
$cat->save();
$redirect->withCookie(cookie('cat_id', $cat->id,10000));
}
return $redirect;
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(); ?>
I am trying to port my web app from laravel 4 to 5 but I am having issues in that one of my model classes is not found.
I have tried to utilize namespacing and have the following my Models which are located locally C:\xampp\htdocs\awsconfig\app\Models
the file which the error appears in looks like
<?php
use App\Models\SecurityGroup;
function from_camel_case($input)
{
preg_match_all('!([A-Z][A-Z0-9]*(?=$|[A-Z][a-z0-9])|[A-Za-z][a-z0-9]+)!', $input, $matches);
$ret = $matches[0];
foreach ($ret as &$match)
{
$match = $match == strtoupper($match) ? strtolower($match) : lcfirst($match);
}
return implode('_', $ret);
}
$resource_types = array();
$resource_types['AWS::EC2::Instance'] = 'EC2Instance';
$resource_types['AWS::EC2::NetworkInterface'] = 'EC2NetworkInterface';
$resource_types['AWS::EC2::VPC'] = 'VPC';
$resource_types['AWS::EC2::Volume'] = 'Volume';
$resource_types['AWS::EC2::SecurityGroup'] = 'SecurityGroup';
$resource_types['AWS::EC2::Subnet'] = 'Subnet';
$resource_types['AWS::EC2::RouteTable'] = 'RouteTable';
$resource_types['AWS::EC2::EIP'] = 'EIP';
$resource_types['AWS::EC2::NetworkAcl'] = 'NetworkAcl';
$resource_types['AWS::EC2::InternetGateway'] = 'InternetGateway';
$accounts = DB::table('aws_account')->get();
$account_list = array();
foreach(glob('../resources/sns messages/*.json') as $filename)
{
//echo $filename;
$data = file_get_contents($filename);
if($data!=null)
{
$decoded=json_decode($data,true);
if(isset($decoded["Message"]))
{
//echo "found message<br>";
$message= json_decode($decoded["Message"]);
if(isset($message->configurationItem))
{
// echo"found cfi<br>";
$insert_array = array();
$cfi = $message->configurationItem;
switch ($cfi->configurationItemStatus)
{
case "ResourceDiscovered":
//echo"found Resource Discovered<br>";
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$insert_array[from_camel_case($key)] = $value;
}
}
$resource->populate($insert_array);
if (!$resource->checkExists())
{
$resource->save();
if(isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
$tag->save();
/*if(isset($cfi->awsAccountId))
{
foreach ($accounts as $a)
{
$account_list = $a->account_id;
}
if (!in_array($account_id,$account_list))
{
$account_id = new Account;
$account_id->aws_account_id = $cfi->awsAccountId;
$account_list[] = $account_id;
$account_id->save();
}
} */
}
}
}
}
else
{
echo "Creating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'ResourceDeleted':
// echo"found Resource Deleted<br>";
//ITEM DELETED
if (array_key_exists($cfi->resourceType,$resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
$resource->delete();
if( isset($cfi->configuration->tags))
{
foreach ($cfi->configuration->tags as $t )
{
$tag= new Tag;
$tag->resource_type = "instance";
$tag->resource_id = $resource->id;
$tag->key = $t->key;
$tag->value = $t->value;
if ($tag->checkExists($cfi->configuration->tags))
{
$tag->delete();
}
}
}
}
}
else
{
echo "Deleting ".$cfi["resourceType"]." not yet supported<br>";
}
break;
case 'OK':
//echo"found Resource OK<br>";
//ITEM UPDATED
if (array_key_exists($cfi->resourceType, $resource_types))
{
//var_dump($cfi->resourceType);
$resource = new $resource_types[$cfi->resourceType];
if ($resource->checkExists($cfi->resourceId))
{
foreach ($cfi->configuration as $key => $value)
{
if (in_array($key,$resource->fields))
{
$update_array[from_camel_case($key)] = $value;
}
}
$resource->populate($update_array);
$resource->save();
}
}
else
{
echo "Updating ".$cfi["resourceType"]." not yet supported<br>";
}
break;
default:
echo "Status ".$cfi['configurationItemStatus']." not yet supported<br>";
break;
}
}
}
}
}
and the corresponding model whose class cannot be found looks like :
<?php namespace App\Models;
use Eloquent;
class SecurityGroup extends Eloquent
{
protected $table = 'security_group';
public $timestamps = false;
protected $guarded = array('id');
public $fields = array('groupId',
'groupName',
'description',
'ownerId'
);
public function checkExists()
{
return self::where('group_id', $this->group_id)->first();
}
public function populate($array)
{
foreach ($array as $k => $v)
{
$this->$k = $v;
}
}
}
I am lost as to what is causing the problem I don't see any typos but then again who knows as always thanks for any help given.
to solve the resource type needs the full namespace declaration
I am trying to store some data as an array in the session but the function does not seem to be working.it does not throw any error but every time i add data to it, it just overwrites the previous data. I am using yii and here is the action
public function actionStoreProducts($name)
{
$name=trim(strip_tags($name));
if(!empty($name))
{
if(!isset(Yii::app()->session['_products']))
{
Yii::app()->session['_products']=array($name);
echo 'added';
}
else
{
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['products'] = $myProducts;
echo 'added';
}
}
Can anyone suggest me how can i achieve the desired result?
Please correct your code like this .
public function actionStoreProducts($name) {
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
Yii::app()->session['_products'] = array($name);
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
Yii::app()->session['_products'] = $myProducts;
echo print_r(Yii::app()->session['_products']);
echo 'added';
}
}
}
session property read-only
i think the correct aproach is :
function actionStoreProducts($name) {
$session = new CHttpSession; //add this line
$session->open(); //add this line
$name = trim(strip_tags($name));
if (!empty($name)) {
if (!isset(Yii::app()->session['_products'])) {
$session->add('_products', array($name)); //replace this line
echo 'added';
} else {
$myProducts = Yii::app()->session['_products'];
$myProducts[] = $name;
$session->add('_products', $myProducts); //replace this line
echo 'added';
}
}
}
first get an variable into $session['somevalue'] ,then sore in array variable, Use Like IT:-
$session = new CHttpSession;
$session->open();
$myval = $session['somevalue'];
$myval[] = $_POST['level'];
$session['somevalue'] = $myval;
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