Wouldn't the if statement in this PHP function be useless? - php

I am trying to work on someones code and ran into this.
private function getAttImages($limit, $forumIds = 0, $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null)
{
$fids = '';
if ($forumIds)
{
$r = '';
if ($fidsReverse)
{
$r = ' NOT ';
}
if (is_array($forumIds))
{
$forumIds = implode(',', $forumIds);
}
$fids = ' AND forums_topics.forum_id ' . $r . ' IN (' . $forumIds . ')';
}
function continues to other things. However, the question is that first if statement if($forumIds) wouldn't it be useless if every time this function is called $forumIds is set to 0 ?

This is the default value for this function if nothing else is specified. It means that if nothing is entered when calling the function, it will default be 0 and the function will essentially do nothing.
Examples:
getAttImages(5, 1)
Will essentially set $limit to 1 and $forumids to 1. The rest of the parameters will be set to their default values as nothing is entered ( $fidsReverse = false, $topicIds = 0, $membersIds = 0, $order = 'attach_date', $sort = 'desc', $group = null )
The only required parameter is limit as it has no default value in it. So, at minimum the function can be called like so:
getAttImages(0); and the rest will just default to the values defined in the function. However, this code won't do anything as $forumIds will be 0.

No. $forumIds is set to zero in the function parameters, but that zero is only applied to $forumIds if someone calls the function but does not explicitly set a value for that parameter.

The code
..., $forumIds = 0, ...
is setting up the default for that variable. It can be overridden with any value when called, but will default to 0 if no value for $forumIds is provided.
See the PHP documentation: http://php.net/manual/en/functions.arguments.php#functions.arguments.default.

Related

Best way of handling pagination in a PHP client library

Assume I have a REST API that supports pagination (and filtering). Upon executing a GET request to myapi.com/api/users, it returns something like this:
{
total: 100
data: . . .
first_page_url: "/?page=1"
from: 0
next_page_url: "/?page=2"
path: "/"
per_page: 10
prev_page_url: null
to: 10
}
And then in my PHP client library I have something similar to this for a function that performs this request and returns the JSON response as an associative array:
public function users($page = 1, $verified = null, $admin = null, $joined = null, $active_until = null, $banned_until = null, $referral_code = null) {
. . .
}
What would be the best way to fetch the next result?
I am envisioning something like this:
$users = [];
$request = users(); // gets the first page
while ($request) {
$request = next_users();
array_push($users, $request['data']);
}
The problem is that I have no idea where to begin when it comes to putting the result of users() into next_users() while preserving any filter values (the optional parameters of users()), all while doing it elegantly. I have tried looking around, but I can't find many results of API clients handling pagination. As demonstrated above, the ideal scenario would be having the ability to keep getting the next page of results until there are none left with next_users().
You just keep your filter and go through all pages. Something like this:
$filter = [
$admin = true,
$joined = null,
$active_until = null,
$banned_until = null,
$referral_code = "RJ08"
];
$page = 1;
$response = users($page, ...$filter); // gets the first page
$usersData = $response['data'];
while (null !== $response['next_page_url']) {
$response = users(++$page, ...$filter);
array_push($usersData, $response['data']);
}

create dynamic tree using php

I have a code for dynamic tree view using php mysql.
function fetchCategoryTreeList($parent = '', $user_tree_array = '')
{
// code here
}
i just want ...like. i have a variable
$top = '1234';
now how to put in this function like
function fetchCategoryTreeList($parent = $top, $user_tree_array = '')
{
// code here
}
if i put $top in this function then i got fatal error. Please help me
You cant assign default value as another variable to arguments. You can use constant instead
define("TOP", "1234");
function fetchCategoryTreeList($parent = TOP, $user_tree_array = '')
{
// code here
}
If you really need a default dynamic value :
$top = '1234' ;
// Some code
function fetchCategoryTreeList($parent = '', $user_tree_array = '')
{
global $top ;
if ( $parent == null || $parent == '' ) $parent = $top ;
// code here
}
But if the value is constant take a look at B Desai answer.

call a function by omitting function argument

function givemeposts($user, $pos){
$sql = "select * from posts where user ='" . $user . "' and pos = '" . $pos . "' order by inde";
...
givemeposts('public', 'home01'); // this works as usual
Now I nedd to call the above function, but without $pos param, i.e. whatever $pos value is.
Something like:
givemeposts('public', whatever);
Any way to do this?
You can use default parameter :
function givemepost( $user , $pos=NULL ){
if($pos==NULL){
//some code
}lese{
$sql = "select * from posts where user ='" . $user . "' and pos = '" . $pos . "' order by inde";
}
}
This way you can call the function with one paramter, and set what the function have to do, inside the if branch.
In PHP you can set default values for arguments
The default value must be a constant expression, not (for example) a variable, a class member or a function call.
Note that when using default arguments, any defaults should be on the right side of any non-default arguments; otherwise, things will not work as expected.
If you do this, the default value for $pos will be '' (an empty string):
function givemeposts($user, $pos = ''){
Or you can something else than an empty string, whatever value you want:
function givemeposts($user, $pos = 'SomeValue'){
Then you can simply call your function like this:
givemeposts($user);
You can try this:
function givemeposts($user, $pos = '')
{
if(!empty($pos)) {
$pos = "AND pos = '" . $pos . "'";
}
$sql = "SELECT * FROM posts WHERE user ='" . $user . "' $pos ORDER BY inde";
}
givemeposts('public');

MySQL Update with field being a concatenated string

function updateUser($userData, $statsID) {
$fields = '';
$config = 0;
while(list($key,$val)= each($userData)) {
if($config++ != 0){
$fields .= ' , ';
}
$col = $key;
$val = $val;
$fields .= "$col='$val'";
}
//echo $fields;
global $dbhandle;
$query = mysqli_query($dbhandle, "UPDATE data SET $fields WHERE statsID = '$statsID'");
echo var_export($query); <--returns NULL
In this code, I pass in an array as noted below:
$sendData = array('name'=>$name,'race'=>$race,'rank'=>$rank,'highestRank'=>$highestRank,'commander'=>$commander,'atkSld'=>$atkSld,'atkMerc'=>$atkMerc,'defSld'=>$defSld,'defMerc'=>$defMerc,'untSld'=>$untSld,'untMerc'=>$untMerc,'spies'=>$spies,'sentries'=>$sentries,'morale'=>$morale,'tff'=>$tff,'strike'=>$strike,'strikeRank'=>$strikeRank,'defense'=>$defense,'defenseRank'=>$defenseRank,'spy'=>$spy, 'spyRank'=>$spyRank, 'sentry'=>$sentry, 'sentryRank'=>$sentryRank, 'fort'=>$fort,'siege'=>$siege,'economy'=>$economy,'tech'=>$tech,'conscription'=>$conscription,'gold'=>$gold,'tbg'=>$tbg,'gameTurns'=>$gameTurns,'covertLvl'=>$covertLvl);
I have confirmed all the data is set and correct. The statsID passes in correctly and when I echo field, it gives me exactly what is required to fulfill my query and in the correct format (key='value' , key ='value' , key ='value etc)
EDIT: Problem solved, I have updated my code to reflect the solution. For some reason I had to call global $dbhandle prior to the query string. If someone could tell me why that would be great!

MySQL query code using the OR for two different fields with Web Service

Normally I can figure this out, but the format looks a bit different then what I am used to. I have a web service using php with CodeIgnighter. The function looks like this:
function getCurrentSales($office_id)
{
$CI =& get_instance();
$CI->load->model("properties");
//Get the properties
$where = array('field_SaleOfficeCode'=>$office_id);
$where = array('field_ListOfficeCode'=>$office_id);
$result = $CI->properties->getCurrentSales($where);
$properties = $result->result_array();
foreach($properties as $p){
//Get property images
$where = array('ListingKey'=>$p['UniqueKey']);
$property_arr[] = $p;
}
return $property_arr;
}
$this->nusoap_server->service(file_get_contents("php://input"));
}
What I am trying to do is return rows where field_ListOfficeCode or field_ListOfficeCode have the value of $office_id. As it is now, only when field_ListOfficeCode=>$office_id, not when one or the other equals the value.
Models Method Code:
function getCurrentSales($where = null) {
$this->db->select('field_ListingKey as UniqueKey,
field_LocaleListingStatus as Status,
field_CloseDate as ClosingDate,
field_ContractDate as ContractDate,
field_ListingID as MLS,
TRIM("#VARIES" from field_FullStreetAddress) as StreetAddress,
field_ListPrice as Price,
field_ListOfficeCode as BrokerID,
if(field_Beds != "", field_Beds, 0) as NumBeds,
if(field_BathsFull != "", field_BathsFull, 0) as NumFullBaths,
if(field_BathsHalf != "", field_BathsHalf, 0) as NumHalfBaths,
field_InternetRemarks as PropertyRemarks,
field_ListOfficeName as ListingOfficeName,
field_ListPicture3URL as MainPhoto,
CONCAT(field_ListAgentNickname, " ", field_ListAgentLastName, " ", (if(field_ListAgentNameSuffix = "NULL", field_ListAgentNameSuffix, ""))) as ListingAgent,
CONCAT(field_SaleAgentNickname, " ", field_SaleAgentLastName, " ", (if(field_SaleAgentNameSuffix = "NULL", field_SaleAgentNameSuffix, ""))) as SalesAgent,
CONCAT(field_City, ", ", field_State, " ", field_PostalCode) as AreaAddress', false);
$this->db->from('TABLE_2');
if($where != null){
$this->db->where($where, false);
$this->db->where('YEAR(field_ContractDate) = YEAR(NOW())', NULL, false);
$this->db->where('MONTH(field_ContractDate) = MONTH(NOW())', NULL, false);
}
$this->db->order_by('ContractDate', 'desc'); //get random row
//$this->db->limit($limit);
$query = $this->db->get();
return $query;
}
I'm not familiar with CodeIgniter, but I would suspect your problem is with these two lines
$where = array('field_SaleOfficeCode'=>$office_id);
$where = array('field_ListOfficeCode'=>$office_id);
You aren't actually building up an array of where clauses, but rather overriding the first assignment with the second, which explains why you are only getting results that match field_ListOfficeCode == $office_id
Depending on how CodeIgniter expects these where clauses to be formed, I would assume it should be something like
$where = array(
array('field_SaleOfficeCode'=>$office_id),
array('field_ListOfficeCode'=>$office_id)
)
Or from a quick look at the documentation
$where = array(
'field_SaleOfficeCode'=>$office_id,
'field_ListOfficeCode'=>$office_id
)
And then in your getCurrentSales function, it should be
$this->db->or_where($where)

Categories