receive returned value by class in oop - php

i have a class like this :
<?php
class connection {
public $db;
public function __construct() {
$this->db = new mysqli('localhost', 'root', '', '');
if($this->db->connect_errno > 0){
die('error ' . $this->db->connect_error);
}
$this->db->set_charset("utf8");
}
}
class masssave extends connection {
public $sql;
public function insert_all {
// do some works
if ( $sql = $this->db->query("INSERT INTO $db_name ($str_db_value) values ($str_form_value_found) ")) {
return true;
}
else {
return false;
}
}
}
?>
in masssave class i seted $sql as public , now i want to use this class in some pages , like register page
$save = new masssave;
if ( $save->sql = true ) {
echo 'ok';
}
else {
echo 'failed';
}
but the upper code is not working , it always echo 'ok' even the query was failed ,
i also use if ( $save->sql == true ) but this code always echo 'failed'
i am newbie in oop , but i think my php classes are ok , i think i am doing wrong way for checking returned value

replace $sql = $this->db->query with $this->sql = $this->db->query -- $sql - local variable. $this->sql - object property
call proper method after $save = new masssave; use $save->insert_all()
use comparison (but not assigment) $save->sql = true - assigment, $save->sql == true - comparison. Assigment reutrns value of variable, so $save->sql = true is always true.

This line should be...
if ( $save->insert_all() == true )
Because....First off, you are just checking if $save->sql is set, which will always echo true in your case.
Also you weren't even checking you were actually setting (= vs ==)
$save = new masssave;
if ( $save->sql = true )
Should be...
$save = new masssave;
if ( $save->sql == true ) {
But that will always return true anyways, because its just checking if the variable exists, which it does. What you really want is what I posted at the top. Because query is actually inside the insert_all function, which is where you are returning true or false.

It will always echo ok because you're setting the $save->sql to true
if ( $save->sql = true ) {
The above is a big NO NO.
What you want is to compare it, so using == to compare the values
if ( $save->sql == true ) {
It would be simpler to just do:
if($save->sql) {
echo 'ok;
} else {
echo 'fail';
}
the above if check is basically saying IF(TRUE) { SAY OK} ELSE { SAY FAIL}

Related

get results returned in a function

i have this inside a php function:
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
so its returning all of the values in the $result variable
when i do a print_r on the function, the results display like this:
stdClass Object
(
[domainname] => domain.com
[element] =>
[availability] => false
)
i am calling the function with this code:
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
so i tried to get the returned by doing $domain->availability but its not returning the value, example:
if($domain->availability) {
echo 'yes';
} else {
echo 'no';
}
am i trying to get the data the incorrect way?
UPDATE
the full function is:
if(!function_exists("domainNameCheck")) {
function domainNameCheck($domainName, $element) {
$result = '';
$client = new IcukApiClient();
$client->username = "username";
$client->key = "pass";
$client->encryption = "SHA-512";
$req = new IcukApiRequest();
$req->url = "/domain/availability/" . $domainName;
$req->method = "GET";
$res = $client->send($req);
$availability = 'unknown';
if ($res->success) {
$obj = json_decode($res->response);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}
$result = new stdClass();
$result->domainname = $domainName;
$result->element = $element;
$result->availability = $availability;
return ($result);
}
}
Your main problem seems to be that you are calling a function with 2 parameters but passing only one parameter
function domainNameCheck($domainName, $element) {}
// called like this (one parameter)
$domain = domainNameCheck($_GET["domain"].'.'.$_GET["tld"]);
This should be generating a compile error!
Also here
if ($res->success) {
$obj = json_decode($res->response);
// check what $obj->available is set to
// it may also be a string and not a boolean
print_r($obj);
$availability =($obj->available) ? 'true' : 'false';
}
else {
$availability = 'unknown';
}
Please note that there are two error/warning messages PHP is giving:
E_WARNING : type 2 -- Missing argument 2 for domainNameCheck()
E_NOTICE : type 8 -- Undefined variable: element
You should fix those errors, and make sure you are informed of errors during development.
Secondly, you have defined your availability as a string by assigning "false", "true", or "unknown". So when you do this:
if($domain->availability) {
... that will be true for all three values, because strings are true for PHP when converted to boolean (except when empty). To illustrate, this will echo "hello":
if ("false") echo "hello";
So you need to change your test like this:
if($domain->availability === "true") {
Or, If you want to define $domain->availability as a true boolean, then you need to alter the assignments in your function, like this:
....
$availability = $obj->available; // assuming that is a boolean!
}
else {
$availability = null; // unknown
}
... and then you can do what you had:
if($domain->availability) {
Likely because $domain->availability is boolean
To output you can first check whether its true or false and output accordingly
here's a simple example:
if ($domain->availability){
echo 'Available';
}
else {
echo 'Not Available';
}

in specific condition set and store a variable until another specific condition

Hello I'm pretty new in programming. I need to solve this problem in php but the solution in any different language will be great. I tryied to solve it with if statement but if condition is changed the variable is gone. Easy example for better understanding.
// possible conditions ( 'cond1', 'cond2', 'cond3', 'cond4','cond5' )
// conditions can be called randomly
I would like to have somethng like this:
$variable = 'off';
since ( $condition == 'cond2' )
$variable = 'on';
until ( $condition == 'cond4' )
The goal is to switch variable 'on' in the 'cond2' condition and hold it on when the others conditions are changing independently on their order until condition is changed to 'cond4' and variable is switched back to 'off'.
Thanks for any suggestions.
I don't think your current concept is realizable in PHP as you cannot listen to variables, you need to actively get notified. So one scenario with the same solution but a different concept would be
class Condition {
private $value;
private $variable = false;
public function setCondition($new_value) {
$this->value = $new_value;
}
public function getCondition() {
return $this->value;
}
public function isVariableSet() {
return ($this->variable === true); //TRUE if $this->variable is true
//FALSE otherwise
}
}
Now in the method setCondition(...) you can listen and actively set the variable.
public function setCondition($new_value) {
switch ($new_value) {
case 'cond2':
$this->variable = true;
break;
case 'cond4':
$this->variable = false;
break;
}
$this->value = $new_value;
}
With this you can use it like the following
$foo = new Condition();
$foo->setCondition('cond1');
var_dump( $foo->isVariableSet() ); //FALSE
$foo->setCondition('cond2');
var_dump( $foo->isVariableSet() ); //TRUE
$foo->setCondition('cond3');
var_dump( $foo->isVariableSet() ); //TRUE
$foo->setCondition('cond4');
var_dump( $foo->isVariableSet() ); //FALSE
Or in your case:
$conditions = array( 'cond1', 'cond2', 'cond3', 'cond4','cond5' );
$cond = new Condition();
foreach ($conditions as $i => $condition) {
$cond->setCondition($condition);
if ($cond->isVariableSet() == true) {
$toggle = 'on';
}
else {
$toggle = 'off';
}
$results[$condition] = $toggle.' ; ';
}
If you don't create the instance of Condition outside the loop, you gain nothing as you create a new object everytime and no state stays. However, exactly that is required.
You can also do this via array_map() and save the foreach()
$conditions = array( 'cond1', 'cond2', 'cond3', 'cond4','cond5' );
$cond = new Condition();
$results = array();
$setCondGetVariable = function($condition) use($cond) {
$cond->setCondition($condition);
if ($cond->isVariableSet() == true) {
$toggle = 'on';
}
else {
$toggle = 'off';
}
return $toggle.' ; ';
};
$results = array_map($setCondGetVariable, $conditions);

PHP return value from class function not working

I am having problem fetching return value returned by a class function in PHP. Does returning values works exactly the way it works in other languages- C, C++, Java or there is something new to it.
This is my Class:
class M_UserMaster
{
private $_db = null;
function __construct($db)
{
$this->_db = $db;
}
function checkUserExists($mobNum)
{
$userExists = false;
$sql = "SELECT STATEMENT HERE";
$stmnt = $this->_db->prepare($sql);
$stmnt->execute();
$numRows = $stmnt->rowCount();
echo '<br><br>Num Rows: ' . $numRows . '<br>***';
$userExists = ($numRows > 0) ? true : false;
return $userExists;
}
}
The echo statement returns 0. But the function returns nothing.
From another file I am calling it like this:
$m_userMaster = new M_UserMaster($db);
$userExists = $m_userMaster->checkUserExists('0000000000');
echo '<br><br>User Exists: ' . $userExists;
This is what is printed
User Exists:
If you do
$x = true;
echo $x;
You will get output 1
But with
$x = false;
echo $x;
You will get empty string as output
You will need to do something like this:
echo '<br><br>User Exists: ' . ($userExists ? 'yes' : 'no');
Or change return value of your function from true / false to 1 / 0. That will behave similar way, but output will be correct.
You are trying to echo a literal boolean value. PHP prints such values as empty strings. You want to do something like this, instead:
echo '<br><br>User Exists: ' . ($userExists ? 'true' : 'false');
This will echo the first part no matter what. It then checks whether $userExists is true. If so, it prints true; otherwise, it prints false.
Try like
$userExists = ($numRows > 0) ? 'true' : 'false';
As per your code,if the $numRows is greater than 0 then it will return 1 and if the $numRows is 0 then it will return empty because it become false.For clear understand
echo true; // Return 1
echo false; // Return empty

Working with PHP functions

I have this function that will check if a user already exists in the DB or not:
function checkTwitterAccount($user_id) {
$accountExists = false;
$a = "SELECT * FROM twitterAccounts WHERE user_id='".$user_id."'";
$ar=mysql_query($a) or die("Error selecting twitter account: ".mysql_error());
$ac = mysql_num_rows($ar);
if ($ac > 0) {
$accountExists = true;
}
return $accountExists;
}
Now when I call this function how do I actually know if the user is or is not in the DB?
I mean how do I call this function and how do I check the result?
Is the below right?
If (checkTwitterAccount($user_id) = true) {
DO THIS
}else{
DO THAT
}
Please help me I am new to it.
Thanks
if (checkTwitterAccount($user_id)) { //true
//do something
} else { //false
//do something
}
if (checkTwitterAccount($user_id) == true) {
//do this
}
else {
//do that
}
You have to use == rather than = as the = operand sets the value to true in the code you wrote, whereas the == operand compares the returned value to true.
Since your returning a true or false value you can simply use:
If (checkTwitterAccount($user_id)) {
//DO THIS
}else{
//DO THAT
}
Note: that your original line:
If (checkTwitterAccount($user_id) = true) {
would result in an assignment error because a single "=" means assign a value which can't be done to a function. You wanted:
If (checkTwitterAccount($user_id) == true) {
because "==" compares a value. Further, == only compares the value so for example 0 is the compares positively with false, any number compares positively with true, if you want to also compare type you us "===" like this:
0 == false //true
0 === false //false
false == false //true
false === false //true
1 == true //true
1 === true //false
true == true //true
true === true //true
function checkTwitterAccount($user_id) {
$user_id = intval($user_id);
$a = "SELECT `user_id` FROM `twitterAccounts` WHERE `user_id` = '".mysql_real_escape_string($user_id)."'";
$ar = mysql_query($a) or die("Error selecting twitter account: ".mysql_error());
$ac = mysql_num_rows($ar);
return ($ac > 0);
}
if(checkTwitterAccount($someid)) {
// Exists...
} else {
// No such ID in the DB
}
Note that comparison operator is == not = (which is assign).
So you could do:
if(checkTwitterAccount($someid) == true) {
However, it isn't necessary here.
Also remember to sanitize the data in the query.
if (checkTwitterAccount($user_id) == true){
do something if its true
} else {
do something if its flase
}
should work.. given that you provide argument to that function which seems to be
the int.. or id number from id column from users table in the db.
Basically you have a HTML Form that takes in a username and checks the database
for that users id number in users table in the database. Once it has this number it will
pass it on to the function checkTwitterAccount($user_id) if that function returns True that means guessing by the name of the function that the user has a twitter account else he does not have one.
you could do:
if (checkTwitterAccount($user_id) == true){
echo "This user has a twitter account";
} else {
echo "This user does not have a twitter account";
}
You can shorten the orig. function.
function checkTwitterAccount($user_id) {
$a = "SELECT * FROM twitterAccounts WHERE user_id='" . $user_id . "'";
$ar = mysql_query($a) or die("Error selecting twitter account: " . mysql_error());
return mysql_num_rows($ar) > 0; // boolean (will be true or false)
}
Then use the answer from max_. (See comparison operators)

PHP Problem: else condition not executing

function procLogin( $user, $pass, $remember, $hostname, $domainame )
{
global $session, $form;
$retval = $session->login( $user, $pass, $remember );
if ( $retval )
{
if ( $session->userlevel == 9 )
if ( $session->isAdmin() )
return ( array(
$session->userlevel, $session->userid
) );
} else {
$process = new process( );
//process->s_Host('domain.com');
//$process->s_Domain('domain.com');
$process->s_Host( $hostname );
$process->s_Domain( $domainname );
$process->s_processSecure( false );
$process->s_User( $user );
$process->s_Pass( $pass );
// First check we actually have a username and password set inside the process object.
if ( $process->g_User() && $process->g_Pass() )
{
if ( $process->processConn() )
{
if ( $process->processBind() )
{
return 'google';
}
}
}
}
}
My problem is if the login is false, why does it not turn towards else condition....
if i remove the code inside else part and put return 'no' it does work.... i just want to know why the code inside the else part does not execute
$session->login(... must somehow always evaluate to true. You would probably be better off posting the code of the login method.
Maybe login is returning "false" as a string? It is evaluating to true because it is not null.
Without a specific error or details of the implementation, or a hint that the PHP runtime or builtin or library is broken ...
This looks like a case of go back, check, debug.

Categories