p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   PHP How-To (http://p2p.wrox.com/forumdisplay.php?f=98)
-   -   Ho to do nested if statements (http://p2p.wrox.com/showthread.php?t=28355)

scoobie April 20th, 2005 10:36 AM

Ho to do nested if statements
 
Hi,

i was wondering if anyone can help me. i have created a form that allows a user to change their email address. when they enter in their old, new and confirm email address and click submit i want the php to perform certain checks such as if the address is in the valid format or if the new email already exists in the database. The problem is these checks are within and if and when i run the code it prints all the echo statements instead of just the section that failed. Here is the code i used.

if ($ModUname)
{
if(!ereg("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $OldUNameFrm, $NewUNameFrm, $ConfUNameFrm))
{
echo "You Must Enter A Valid Email Address.<br>Please Try Again";
}
/*CHECK IF NEW EMAIL EXISTS IN THE DATABASE */
$check = mysql_query("select Username from acctbl where Username = '$NewUNameFrm'");
$result = mysql_query($check);
$num = mysql_num_rows($check);
if ($num > 0)
{
echo "This Email Address Already Exists. Please Try Again";
}
/* CHECK IF NEW AND CONFIRM MATCH */
if ($NewUNameFrm != $ConfUNameFrm)
{
echo "Email Address Don't Match. Please Re-Enter and Confirm Email.";
}
else{
mysql_query("UPDATE acctbl SET Username = '$_POST[NewUNameFrm]'
where Username = '$_POST[OldUNameFrm]'");
echo "Your Email Has Been Successfully Updated";
}
}//end if
else{?
<form method="post" action="<?php echo $PHP_SELF?>">
<b>Change Email</b>
Old Email<input type = "text" name = OldUNameFrm size = "30">
New Email<input type = "text" name = NewUNameFrm size = "30">
Confirm New Email<input type = "text" name = ConfUNameFrm size = "30">
<input type = "Submit" name = "ModUname" value = "Change Email">
</form>
<?php
}//end else
?>

if i put in else if / elseif in the first if statement then the code doesn't run.

can anyone see where i am going wrong?

Thanks in advanced

scoobie


scoobie April 21st, 2005 11:39 AM

It's ok i sorted it. i just took the select query and placed it before the if statement and it works perfectly now.

scoobie


anshul April 24th, 2005 06:22 AM

Ok, u sorted out.
I may say, if there is only a single statement in if or for loop, skipping of curly braces, helps to reduce code-space.
( Besides use of classes, inclues, requires lieu structural functions )

Also switch case branching is better than many if statements.



All times are GMT -4. The time now is 04:33 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.