php parameters passed inside function is not working - php

In php/wordpress I have made a function. I want to pass some parameteres inside the function so that it will show result according to that. So far now my function code is like this
$user_id = get_current_user_id();
function check_user_access($role, $action = NULL ) {
if( $role == 'subscriber') {
if( $action = 'check_customer' ) {
$check_customer = $wpdb->get_var("SELECT COUNT(id) FROM `table1` WHERE `user_id` = $user_id");
return $check_customer;
}
if( $action = 'check_users' ) {
$check_users = $wpdb->get_var("SELECT COUNT(id) FROM `table2` WHERE `user_id` = $user_id");
return $check_users;
}
}
}
Now I am using this function like this
$role = 'subscriber';
$check_customers = check_user_access($role, $action = 'check_users' );
if( $check_users <=1 ) {
//do something;
}
if( $check_users > 1 ) {
//do something other;
}
But its showing the result of $action = 'check_customer'. Means its working for the first block condition. Can someone tell me how to solve this? Am I doing something wrong?

change your
if( $action = 'check_customer' ) {}
to
if( $action == 'check_customer' ) {}
= means Assignment Operator
== means Comparison Operator
refer - from here

Related

Attempt to read property id on bool in Laravel

i tried assigning a value to a variable in an if condition
if ($hotel = Hotel::whereCode($this->hotelCode)->first() && $room = Room::whereRoomCode($value)->first()) {
if ($hotel->room_id == $room->id) {
return true;
}
}
I get this error
Attempt to read property "room_id" on bool
meanwhile $hotel variable is not a boolean
Your code can be processed by the compiler as
if ( $hotel = (
Hotel::whereCode($this->hotelCode)->first() && $room = Room::whereRoomCode($value)->first()
)
) {
//...
}
in that case you can see $hotel is a bool result from the && operator.
You should add parenthesis to counter the issue
if (
($hotel = Hotel::whereCode($this->hotelCode)->first()) &&
($room = Room::whereRoomCode($value)->first())
) {
if ($hotel->room_id == $room->id) {
return true;
}
}
or in a more clear way
$hotel = Hotel::whereCode($this->hotelCode)->first();
$room = Room::whereRoomCode($value)->first();
return $hotel && $room && ($hotel->room_id == $room->id);
Or using relation and using way less performance (using only a count query)
public function hasRoomByRoomCode($value)
{
return $this->room()->whereRoomCode($value)->count();
}
//this is the relation function if you did not set it yet inside Hotel::class
public function room()
{
return $this->belongsTo(Room::class);
}

PHP Pass variable from foreach to function

I'm trying to pass variables from a foreach function that fetch a mysql query to an array, to another function.
I declare the array before the foreach to make it global but no data are passed to the function.
here is my code. If you have any idea of what i'm doing, thanks by advance for your help.
Of course if I replace the called function by what's inside it, everything works like a charm.
but as I'll have to use it several times I would prefer to set my variables in a function.
function fillStuInfos() {
global $studFName, $studLName,c$dateStart, $dateEnd;
$studFName = $EventsGt['fName'];
$studLName = $EventsGt['lName'];
$dateStart = $EventsGt['startDate'];
$dateEnd = $EventsGt['endDate'];
}
$email = $_POST['email'];
$EventsGt = array();
$getEventsQry = 'SELECT * FROM Companies WHERE Email_Company = "'.$email.'" ORDER BY startDate';
foreach ($bddPDO->query($getEventsQry) as $EventsGt) {
$intCur = date_diff(date_create($today), date_create($EventsGt['endDate']));
$intFut = date_diff(date_create($today), date_create($EventsGt['startDate']));
echo intval($intCur->format('%r%a'));
if (intval($intCur->format('%r%a')) <= 4 && intval($intCur->format('%r%a')) > 0 ) {
fillStuInfos();
} else if ( intval($intFut->format('%r%a')) <= 4 && intval($intFut->format('%r%a')) > 0 ){
fillStuInfos();
} else {
echo 'No Datas!';
exit();
}
}
echo $studLName;
Forget that exists global and pass params to function.
function fillStuInfos($data) {
$studFName = $data['fName'];
$studLName = $data['lName'];
$dateStart = $data['startDate'];
$dateEnd = $data['endDate'];
}
...
foreach (...) {
if (intval($intCur->format('%r%a')) <= 4 && intval($intCur->format('%r%a')) > 0 ) {
fillStuInfos($EventsGt);
} else if ( intval($intFut->format('%r%a')) <= 4 && intval($intFut->format('%r%a')) > 0 ){
fillStuInfos($EventsGt);
} else {
echo 'No Datas!';
exit();
}
}
Your variable you want to be global is $EventsGt, not $studFName, $studLName, $dateStart, $dateEnd
With that said, I would recommend passing the event array as a parameter or passing the individual values as parameters instead.

PHP Error - "Warning: Creating default object from empty value in..." [duplicate]

This question already has answers here:
Creating default object from empty value in PHP?
(18 answers)
Closed 7 years ago.
I have a PHP file on my website that is producing errors after upgrading from PHP 5.3 to PHP 5.4. This is the error it produces:
Warning: Creating default object from empty value in (removing this
part of the error)/arcade.php on line 60
This is what the code looks like after like 60:
{
$this->arcade->version = '';
}else
{
$this->arcade->version = '3.4.0';
}
I'm assuming it has to do with the blank value there. I researched some similar fixes, but I'm still having trouble figuring out exactly what I should add to the php file to fix it.
Thank you very much for any help ahead of time!
Edit: Here's the rest of the code I'm not sure where it intializes. I'm pretty ignorant of these things.
if ( ! defined( 'IN_IPB' ) )
{
print "<h1>Incorrect access</h1>You cannot access this file directly. If you have recently upgraded, make sure you upgraded all the relevant files. <br /> <b>File Version 3.3.0</b>";
exit();
}
class component_public
{
var $ipsclass = '';
var $arcade = '';
function run_component()
{
$this->ipsclass->load_language( 'lang_Arcade' );
if( !$this->ipsclass->cache['arcade_settings']['allow_user_skin'] )
{
if( $this->ipsclass->cache['arcade_settings']['skin'] == 0 ) {
$this->ipsclass->load_template('skin_Arcade1');
}
if( $this->ipsclass->cache['arcade_settings']['skin'] == 1 ) {
$this->ipsclass->load_template('skin_Arcade2');
}
if( $this->ipsclass->cache['arcade_settings']['skin'] == 2 ) {
$this->ipsclass->load_template('skin_Arcade3');
}
}else
if( $this->ipsclass->cache['arcade_settings']['allow_user_skin'] && !$this->ipsclass->member['id'] )
{
if( $this->ipsclass->cache['arcade_settings']['skin'] == 0 ) {
$this->ipsclass->load_template('skin_Arcade1');
}
if( $this->ipsclass->cache['arcade_settings']['skin'] == 1 ) {
$this->ipsclass->load_template('skin_Arcade2');
}
if( $this->ipsclass->cache['arcade_settings']['skin'] == 2 ) {
$this->ipsclass->load_template('skin_Arcade3');
}
}else
if( $this->ipsclass->cache['arcade_settings']['allow_user_skin'] && $this->ipsclass->member['id'] )
{
$this->ipsclass->DB->query("SELECT arcade_skin FROM ".$this->ipsclass->vars['sql_tbl_prefix']."members WHERE id=".intval($this->ipsclass->member['id']));
$this->arcade->lib->user = $this->ipsclass->DB->fetch_row();
if( $this->arcade->lib->user['arcade_skin'] == 0) {
$this->ipsclass->load_template('skin_Arcade1');
}
if( $this->arcade->lib->user['arcade_skin'] == 1) {
$this->ipsclass->load_template('skin_Arcade2');
}
if( $this->arcade->lib->user['arcade_skin'] == 2) {
$this->ipsclass->load_template('skin_Arcade3');
}
}
if( !$this->ipsclass->cache['arcade_settings']['build'] )
{
$this->arcade->version = '';
}else
{
$this->arcade->version = '3.4.0';
}
$this->ipsclass->vars['arcade_dir'] = 'arcade';
$component_copyright = '<div class="copyright" align="center">ibProArcade '.$this->arcade->version.' © '.date('Y').'</div>';
$this->ipsclass->skin['_wrapper'] = str_replace("<% COPYRIGHT %>", $component_copyright . "<% COPYRIGHT %>", $this->ipsclass->skin['_wrapper']);
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/db/arcade_mysql.php';
$this->arcade->db = new arcade_db;
$this->arcade->db->ipsclass =& $this->ipsclass;
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/arcadelib.php';
$this->arcade->lib = new arcadelib;
$this->arcade->lib->ipsclass =& $this->ipsclass;
$this->arcade->lib->arcade =& $this->arcade;
$this->arcade->lib->init();
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/scoreboard.php';
$this->arcade->sb = new scoreboard;
$this->arcade->sb->ipsclass =& $this->ipsclass;
$this->arcade->sb->arcade =& $this->arcade;
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/arcadeskin.php';
$this->arcade->skin = new arcadeskin;
$this->arcade->skin->ipsclass =& $this->ipsclass;
$this->arcade->skin->arcade =& $this->arcade;
require_once ROOT_PATH.'sources/api/api_topics_and_posts.php';
$this->arcade->api = new api_topics_and_posts();
$this->arcade->api->ipsclass =& $this->ipsclass;
if( $this->arcade->lib->settings['arcade_status'] )
{
$this->arcade->lib->arcade_error( array( LEVEL => 1, MSG => 'arcade_offlinemsg' ) );
}
$page = (isset($this->ipsclass->input['p'])) ? $this->ipsclass->txt_alphanumerical_clean( $this->ipsclass->input['p'] ) : 'default';
$code = (isset($this->ipsclass->input['code'])) ? $this->ipsclass->input['code'] : '';
// Backwords compatibility with older games
if( isset($this->ipsclass->input['do']) && ($this->ipsclass->input['do'] == 'newscore') )
{
$code = 'newscore';
}
if( isset($this->ipsclass->input['do']) && ($this->ipsclass->input['do'] == 'verifyscore') )
{
$code = 'verifyscore';
}
if( isset($this->ipsclass->input['do']) && ($this->ipsclass->input['do'] == 'savescore') )
{
$code = 'savescore';
}
$file = ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/page_'.$page.'.php';
if( file_exists($file) )
{
require $file;
}
else
{
require ROOT_PATH.$this->ipsclass->vars['arcade_dir'].'/modules/page_default.php';
}
$runme = new arcade_page;
$runme->ipsclass =& $this->ipsclass;
$runme->arcade =& $this->arcade;
$runme->exec_page( $code );
}
}
You got that error if trying to access properties of unexistent objects, like this:
$arcade = null;
$arcade->version = '3.4.0';
In order to fix it, yours $this->arcade property should not be empty.
Upd.
First, remove the line with arcade definition/initialization entirely:
class component_public
{
var $ipsclass = '';
function run_component()
{
$this->ipsclass->load_language( 'lang_Arcade' );
Next, add this piece of code:
class SilentAssasin {
public function __get($property) {
return $this->{$property} = new static();
}
}
class component_public extends SilentAssasin
{
instead of this:
class component_public
{
That must fix that creating from empty error.
Ah, forgot to mention... That SilentAssasin is just a name for custom class, you actually can name it anything you like, like PathosErrorSuppressor or OversizedBanHammerForThatStupidError etc.

Validate with arrays

I'm trying to find a smarter way to validate my inputs with PHP. If the array finds an empty field, it has to add a new element to the array and display an error message.
So far, I haven't succeeded.
The code behind
$felter = array();
if(isset($_POST['submit'])) {
$produktnavn = $_POST['produktnavn'];
$kategori = $_POST['kategori'];
if( !empty( $felter ) ) {
foreach ($felter as $felt) {
if ($felter == '') {
$fejl = true;
}
}
}
else {
$sql = "UPDATE produkt SET produkt_navn = '$produktnavn', fk_kategori_id = '$kategori' WHERE produkt_id=$id";
mysqli_query($db, $sql);
echo "Produktet blev opdateret";
}
Input form
<input type="text" class="form-control" name="produktnavn" value="<?php echo $produktnavn; ?>">
The code starts with $felter = array(); which initializes an empty array.
Then, without changing the array itself, you're checking for non-emptiness of $felter
if( !empty( $felter ) ) {
foreach ($felter as $felt) {
if ($felter == '') {
$fejl = true;
}
}
}
You're trying to iterate over an array that has not gotten any elements pushed into it. And the logic statement if( !empty ($felter)) will also not work as expected either.
As a test, before the check for !empty, put something in the array with $felter[] = 'Test word'; and then, underneath it... (if you're looking for a non-empty array, the logical checker could be if(count($felter)) { before iterating over the array with foreach ($felter as $felt) { if ($felt == '')
$felter = array();
$felter[] = 'Test word';
if(isset($_POST['submit'])) {
$produktnavn = $_POST['produktnavn'];
$kategori = $_POST['kategori'];
if( count( $felter ) ) {
foreach ($felter as $felt) {
if ($felt == '') {
$fejl = true;
}
}
}

How can I rewrite this code to improve its clarity?

Could you write this 'cleaner' ? Just a simple question from a beginner:)
if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
$act = 'tid';
$tid = trim($_GET['tid']);
}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
$act = 'fid';
$fid = trim($_GET['fid']);
}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
$act = 'mid';
}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
$act = trim($_GET['act']);
}else{
$act = "";
}
I would do it like this:
$tid = isset( $_GET['tid'] ) ? trim( $_GET['tid'] ) : '';
$fid = isset( $_GET['fid'] ) ? trim( $_GET['fid'] ) : '';
$mid = isset( $_GET['mid'] ) ? trim( $_GET['mid'] ) : '';
$act = isset( $_GET['act'] ) ? trim( $_GET['act'] ) : '';
if ( empty( $act ) ) // act not set, construct the act from the other GET vars
{
if ( !empty( $tid ) )
$act = 'tid';
else if ( !empty( $fid ) )
$act = 'fid';
else if ( !empty( $mid ) )
$act = 'mid';
}
edit: Of course you could make this even shorter, but the question was how it could be written to “improve its clarity”. And I understand clarity as something that makes it more easy to understand, what happens in a part of code. And I think the actual logic behind the original code gets quite clear with my solution.
I see nothing bad in your code apart from lack of indentation:
if(isset($_GET['tid']) && trim($_GET['tid'])!==""){
$act = 'tid';
$tid = trim($_GET['tid']);
}elseif(isset($_GET['fid']) && trim($_GET['fid'])!==""){
$act = 'fid';
$fid = trim($_GET['fid']);
}elseif(isset($_GET['mid']) && trim($_GET['mid'])!==""){
$act = 'mid';
}elseif(isset($_GET['act']) && trim($_GET['act'])!==""){
$act = trim($_GET['act']);
}else{
$act = "";
}
Although perhaps you could benefit from a function like this
function get_non_empty($field){
return isset($_GET[$field]) && trim($_GET[$field])!='' ? $_GET[$field] : NULL;
}
Definitely not the 'cleanest' solution, but a lot shorter:
$act = '';
foreach(array('tid', 'fid', 'mid', 'act') as $a) {
if(isset($_GET[$a]) && strlen(trim($_GET[$a])) > 0) {
$$a = trim($_GET[$act = $a]);
break;
}
}
This is nearly identical logically to what poke did (+1 for poke for beating me to it), but since we're talking about clarity I thought I'd show my take on it. I like to use FALSE instead of empty strings when it means something isn't being used. It feels like a more explicit way of saying "no". Also, I rarely use the non-bracketed version of if/else but for really short assignment statements I find it way easier to read.
$tid = isset($_GET['tid']) ? trim($_GET['tid']) : FALSE;
$fid = isset($_GET['fid']) ? trim($_GET['fid']) : FALSE;
$mid = isset($_GET['mid']) ? trim($_GET['mid']) : FALSE;
$act = isset($_GET['act']) ? trim($_GET['act']) : FALSE;
if ($act){ // act not set, construct the act from the other GET vars
if ($tid) $act = 'tid';
else if ($fid) $act = 'fid';
else if ($mid) $act = 'mid';
}
Careful with those raw GET values. You should clean those values up before processing them to make sure you are getting exactly what you want, especially if this is about to insert values to a database.
Here is one way. I would however probably do something differently with the tid,fid,mid stuff if I knew what they was intended for.
list($act,$val) = firstValidGETIn('tid','fid','mid','act');
switch($act) {
case 'act': $act = $val; break;
case null : $act = ""; break;
default : $$act = $val;
}
function firstValidGETIn()
{
foreach(func_get_args() as $key)
{
if(array_key_exists($key,$_GET) && trim($_GET[$key]))
return array($key, trim($_GET[$key]));
}
return array(null,null);
}

Categories