i wonder that both if and it's else are true.
i got $apple_id_num from the input select form and it is a number but in string type like "7" and it is how many ids that user wants.so i convert it to integer
now i want to check if it is not more that what i have available in my database.
but statements under conditions ($num_rows<$id_num) and if ($num_rows>=$id_num) both are running.
what i'm doin wrong?
here is my code:
function getAppleID($apple_id_num)
{
$sqli=new mysqlii();
$apple_ids=$sqli->SelectFromDB($apple_id_num);
$num_rows=$sqli->num_rows;
$id_num=(int)$apple_id_num;
if ($num_rows>=$id_num){
$this->printAppleID($apple_ids,$num_rows);
//$sqli->updateRows();
echo"else if running";
return $apple_id_num;
} else if ($num_rows<$id_num)
echo "if statement was rungning";
}
Try this code. always write intended code. Sometimes you may miss a } :P
Use elseif in place of else if.
function getAppleID($apple_id_num)
{
$sqli=new mysqlii();
$apple_ids=$sqli->SelectFromDB($apple_id_num);
$num_rows=$sqli->num_rows;
$id_num=(int)$apple_id_num;
if ($num_rows>=$id_num) {
$this->printAppleID($apple_ids,$num_rows);
//$sqli->updateRows();
echo"else if running";
return $apple_id_num;
} elseif ($num_rows<$id_num) {
echo "if statement was rungning";
}
}
Related
I hope you are doing great. I have a class in my project with various methods. The thing that happens is, one of the methods is supposed to return a Boolean variable. Instead. It returned the number "1" instead of false. If you could tell me where is the problem.
Thanks in advance, Cheers.
Useful pieces of my code:
Class method:
public function validatePwd($pwd1, $pwd2) {
if (strcasecmp($pwd1, $pwd2) == 0)
{
return true;
}
else
{
return false;
}
}
The script that executes it:
$check1 = $user->validatePwd($Password, $Password1);
echo $check1;
if ($user->validatePwd($Password, $Password1))
{
}
else
{
$errors[] = 'Error!, passwords entered are not compatible, Please'
. ' enter passwords that match each other';
}
If you do var_dump($check1) instead of echo $check1; it should show as boolean.
I come across this problem all the time: you have a series of if/else statements, where the intended result can come from two completely different branches, and you end up duplicating the code across both. Here's an example:
if (condition1) {
return error
} else {
if (condition2) {
return intendedResult
} else {
if (condition3) {
return error
} else {
return intendedResult
}
}
}
I have this problem in a PHP script at the moment, where the intended result is approximately 200 lines of PHP queries, HTML and additional if/else statements. Is this the prime example of when you should use a function? And return all that code in a concatenated string?
EDIT:
Thanks for all your replies. I can see that my logic would need tidying up. If I gave you a real-world example, could you help me restructure my logic? I think it's a little more complicated than my pseudo-code.
I pull two dates, $lift_deadline and $show_guide_close from a database, and depending on today's date's relation to those, do the following:
if ($lift_deadline > $today) {
echo "No access until " . $lift_deadline;
} else {
if ($lift_deadline !== "0000-00-00") {
if ($today > $show_guide_close) {
$use_date = $show_guide_close;
} else {
$use_date = $lift_deadline;
}
echo "HTML Table"; // Intended result goes here, using $use_date
} else {
if ($show_guide_close > $today) {
echo "No access until " . $show_guide_close;
} else {
$use_date = $show_guide_close;
echo "HTML Table"; // Intended result also goes here
}
}
}
Well part of the solution is certainly making intendedResult code into a separate method, but just reoganizing the conditions can help:
if ($condition1) {
return 'error';
}
if (!$condition2 && $condition3) {
return 'error';
}
return $this->intendedResult();
This could be further simplified to:
return ($condition1 || $condition3) ? 'error' : $this->intendedResult();
But that might not be as readable, and doesnt really illustrate my point, which is as Tom mentions, to flatten your control structure
Yes, functions are one way to simplify code and make it easier to read. It might be also worth looking into classes and exceptions.
In simple instances I use a switch statement for stuff like this
switch(true)
{
case (condition1):
break;
case (condition2):
break;
default:
}
I have the following code to validate form data. I have created functions to validate various groups, and then have an if isset statement to check if these functions return true. I have tried many different ways to get this to work.
The problem I am having is this. I want the if isset to end if returning FALSE; but it doesn't, it keeps going and pops up the next alert (in my code I have many functions). How can I get it to exit after the first return FALSE? Do I need to make the isset into a function? So it can exit on return FALSE. thanks
I am having trouble writing a function to call functions in php.
function namecheck ($fname, $lname)
{
$regexp ="/^[A-Za-z]+$/";
//filter through names
if (preg_match($regexp,$fname,$lname))
{
return TRUE;
}
else
{
echo'<script type="text/javascript">alert("Enter your names.")</script>';
return FALSE;
}
}
function emailcheck ($email1, $email2)
{
$regexp="/^[a-zA-A-Z0-9_.]+#[a-zA-Z0-9-]+\.[a-zA-Z0-9.-]+$/";
//validate email address
if (preg_match($regexp,$email1,$email2))
{
return TRUE;
}
else
{
echo '<script type="text/javascript">alert ("Enter a valid email address.")</script>';
return FALSE;
}
}
$fname=$_POST['fname'];
$lname=$_POST['lname'];
$namecheck=namecheck($fname,$lname);
$email1=$_POST['email1'];
$email2=$_POST['email2'];
$emailcheck=emailcheck($email1,$email2);
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck!==TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
A general structure for your functions you could follow is something like this:
function validateName($name) {
// Do Validation. Return true or false.
}
function validateEmail($email) {
// Do Validation. Return true or false.
}
function isFormValid()
{
// Name Validation
if( ! validateName( $_POST['name'] ) )
return false;
// Email Validation
if( ! validateEmail( $_POST['email'] ) )
return false;
// Form is valid if it reached this far.
return true;
}
// In your regular code on Form Submit
if( isset($_POST['submit']) )
{
if( isFormValid() ) {
// Save Form Data to DB
} else {
// Show Some Errors
}
}
That general structure should work fine for you. It could be made a LOT better but, for the sake of learning, this is sufficient.
If you want the script to, as you put, "exit" then you need to use exit(); Generally this is bad as the script will completely stop executing. Maybe you can look into using "break;" to get you out of a loop and stop executing functions within that loop. Another problem is that you are echoing out HTML code in your function which gets executed on assignment and so you will always get an alert generated when it evaluates to FALSE.
edit:
within your if(isset()) block. Inside here you can do{}while(false); which is a loop and will let you break out of it at anytime and prevent further execution of code within that loop.
If a function isn't returning false, then it never reached a return FALSE; statement. It's as simple as that. So let's examine the relevant code:
if (isset($_POST['submit']))
{
if ($namecheck !==TRUE)
{
return FALSE;
}
elseif ($emailcheck !== TRUE)
{
return FALSE;
} //and so on..
else
{
return TRUE;
}
}
So, if $_POST['submit'] is set and is not null, the if block will be reached. Then, if $namecheck is not true OR $emailcheck is not true, the function will return FALSE. You can simplify the above code to just:
if (isset($_POST['submit']))
{
return !(!$namecheck || !$emailcheck);
}
However, it doesn't look like this code is inside a function, so the return statement will do nothing. You have to put it in a function if you want it to work like a function.
Beyond that, I can't help you. I don't know what you want to do with this code. You seem to know how to use and call functions, so I'm not sure what the problem is. If you want to return from a function, put code in a function and call return. Right now your code is not in a function, so return won't do anything.
I have tested each method individually with default values and it all seems to work. There is something going on when they are all mixed together.
Here is the code and i'll do my best to write it in an easy to follow way:
Starting with the controller:
if ($active['newcliq'])
{
$newcliqid = $this->create_m->create_keyword($cliq, $cliqid);
if (!$newcliqid) {
echo json_encode(array('success' => false));
} else {
$this->logic_m->change_active($newcliqid, $cliq);
}
}
$active['newcliq'] is true or false and pulled from userdata('active')
Of course, the next thing it runs is create_keyword($cliq, $cliqid) seen below:
$this->db->insert('cliq', $insert);
$newcliqid = $this->db->insert_id();
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
Again, I have checked it all manually, and I know that $newcliqid is returning the correct insert_id and the overall function is returning the correct value.
So $newcliqid is returned to the controller and goes runs logic_m->change_active seen below:
if (!$this->logic_m->cliqidcheck($cliqid)){
$cliqid = 6;
}
The above line is what is giving me problems. No matter what value, $cliqid is ALWAYS set to 6. Whether cliqidcheck returns true or false.
Here is cliqidcheck($cliqid)
public function cliqidcheck($cliqid)
{
if ((ctype_digit($cliqid)) AND ($this->checkcliqidexist($cliqid)))
{
return true;
} else {
return false;
}
}
I have tested cliqidcheck with manually entered values and it always returns the correct value. In addition, i've flat out removed the cliqidcheck from the change_active model and it works perfectly.
I also echo'ed the variable $newcliqid in the controller and found the correct value.
I am hoping this is just a simple problem that I'm overlooking. Thanks for the help! Please let me know if more info is required.
Instead of verbal explanations, wouldn't be it better to post either the debugging code
var_dump($cliqid);
$tmp = $this->logic_m->cliqidcheck($cliqid);
if (!$tmp) {
$cliqid = 6;
}
var_dump($tmp, $cliqid);
die;
and it's output.
Even without posting it here it will convince you that if statement actually never "running regardless of true false"
Setting full error reporting also helps (with finding typos and such)
ini_set('display_errors',1);
error_reporting(E_ALL);
Also a note on excessive code. This statement
if (condition)
{
return true;
} else {
return false;
}
can (and should, in my opinion) be shortened to
return (condition);
Same goes for insert id. Why not to make it just
return $this->db->insert_id();
without all that windy
if ($newcliqid) {
return $newcliqid;
} else {
return false;
}
which is actually a mere tautology
<?php
function testEnd($x) {
if ( ctype_digit($x) ) {
if ( $x == 24 ) {
return true;
exit;
} else {
return false;
exit;
}
} else {
echo 'If its not a digit, you\'ll see me.';
return false;
exit;
}
}
$a = '2';
if ( testEnd($a) ) {
echo 'This is a digit';
} else {
echo 'No digit found';
}
?>
Is exit needed along with return when using them inside a php function? In this case, if anything evaluated to false, i'd like to end there and exit.
No it's not needed. When you return from a function then any code after that does not execute. if at all it did execute, your could would then stop dead there and not go back to calling function either. That exit should go
According to PHP Manual
If called from within a function, the return statement immediately
ends execution of the current function, and returns its argument as
the value of the function call. return will also end the execution of
an eval() statement or script file.
Whereas, exit, according to PHP Manual
Terminates execution of the script.
So if your exit was really executing, it would stop all the execution right there
EDIT
Just put up a small example to demonstrate what exit does. Let's say you have a function and you want to simply display its return value. Then try this
<?php
function test($i)
{
if($i==5)
{
return "Five";
}
else
{
exit;
}
}
echo "Start<br>";
echo "test(5) response:";
echo test(5);
echo "<br>test(4) response:";
echo test(4);
/*No Code below this line will execute now. You wont see the following `End` message. If you comment this line then you will see end message as well. That is because of the use of exit*/
echo "<br>End<br>";
?>