Jump to content

super simple, if( $v_name == "" || $v_msg == "" ) into a switch?


phpchick

Recommended Posts

Hi, I currently have an if, elseif, else program that starts off with

 

if( $v_name == "" || $v_msg == "" )
echo "something"

 

how do I turn this into a switch?

 

but the very next elseif I have

 

elseif( strcspn( $_REQUEST['msg'], '0123456789' ) == strlen( $_REQUEST['msg'] ) )
echo "something"

 

is it possible to turn this into a switch with 2 different strings like that to evaluate?

Link to comment
Share on other sites

because there will be a lot of conditions that I want to check through and with nested if statements it will be too confusing.

 

I am building a signup form for a website.

 

 

if a person enters an invalid password or email, it must say "you must enter a valid email and password"

if there is no number, it must display "you must use at least a number.

if there is no special character, it must display "you must use at least 1 special character"

if there is less than 8 characters, it must display "you must enter at least 8 characters"

if there is no capital letters, it must display "At least one letter must be capitalized"

Link to comment
Share on other sites

Don't nest them then. Just do all the error checking in separate statements. Something like this:

 

<?php

$error = false;
$erros = array();

if(invalidEmail($email)){
    $error = true;
    $errors[] = "Invalid email address";
}

if(strlen($postedText) < {
    $error = true;
    $errors[] = "Must be 8 or more characters";
}

// etc...

if($error){
    // handle errors here
    foreach($errors AS $singleError){
        echo $singleError . "<br />\n";
    }
}else {
    // no errors caught
    // perform needed task
}

?>

Link to comment
Share on other sites

That is truly a bad way of validating data and presenting errors. You should perform ALL validations at the same time, and present ALL error messages to the user, along with redisplaying the form with their previous entries pre-populated in the fields. Here's my stock 'example' form. Paste it in to a new script, and study how it works. It should give you some ideas on form error handling, storing errors in arrays and adding some field styling in response to validation results.

 

<?php
if( isset($_POST['submitted']) && $_POST['submitted'] == 'yes' ) { //check for hidden field value to indicate form has been submitted
$errors = array(); // initialize an array to hold validation errors
$_POST = array_map('trim', $_POST); // trim all $_POST array values

if( !empty($_POST['name']) ) { // validate the name field
	if( !ctype_alpha($_POST['name']) ) {
		$errors['name'][] = 'Name must be alphabetic characters only.'; // if name has non alpha chars, store error
	}
	if( strlen($_POST['name']) < 3 || strlen($_POST['name'] > 20) ) {
		$errors['name'][] = 'Name must be from 3 to 20 characters.'; // if name has too many/few chars, store error
	}
} else {
	$errors['name'][] = 'Name is a required field.'; // if name is empty, store error
}

if( !empty($_POST['number']) ) { // same validations as in name, above.
	if( !ctype_digit($_POST['number']) ) {
		$errors['number'][] = 'Number must be numeric.';
	}
	if( strlen($_POST['number']) < 5 || strlen($_POST['number']) > 10 )  {
		$error = 'Number must be from 3 to 20 digits. It is currently ' . strlen($_POST['number']) . ' digit';
		$error .= strlen($_POST['number']) == 1 ? '.' : 's.';
		$errors['number'][] = $error;
	}
} else {
	$errors['number'][] = 'Number is a required field.';
}
if( !empty($errors) ) {  // if the $errors array is not empty, display the errors to allow the user to correct them and resubmit the form
	$echo = array();
	foreach( $errors as $v ) {
		if( is_array($v) ) {
			$echo[] = implode('<br>', $v );
		} else {
			$echo[] = $v;
		}
	}
	$err_echo ="<font color=\"red\">The following errors were detected:<br>";
	$err_echo .= implode("<br>\n", $echo);
	$err_echo .= '</font>';
}
}
if( (isset($_POST['submitted']) && !empty($errors)) || !isset($_POST['submitted']) ) {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css" media="screen">
body {
font-family: helvetica, arial, sans-serif;
font-size: 0.85em;
line-height: 1.25em;
letter-spacing: -0.5px;
}
input {
border: 1px solid #336699;
padding: 0.1em;
margin: 5px;
color: #113366;
}
input.error {
background-color: #F2BDCA;
color: #850310;
border: 1px solid red;
}
input.good {
background-color: #D3F5D3;
border: 1px solid #156B15;
color: #156B15;
}
input.submit {
background-color: #CCCCCC;
border: 1px solid #888888;	color: #333333;
padding: 2px;
margin: 0;
font: 0.9em helvetica, arial sans-serif;
}
</style>
<title> Work In Progress</title>
</head>
<body>
<?php
echo !empty($err_echo) ? $err_echo : '';
?>
<form method="post" action="">
Name (3-20 letters):
<input type="text"
class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['name']) ? 'error' : 'good'; } ?>"
name="name"
value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
<br>
Number (5-10 numbers):
<input type="text"
class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['number']) ? 'error' : 'good'; } ?>"
name="number" value="<?php echo isset($_POST['number']) ? $_POST['number'] : ''; ?>">
<br>
<input type="hidden" name="submitted" value="yes">
<input class="submit" type="submit" name="submit" value="
<?php echo !empty($errors) ? 'Re-Submit' : 'Submit'; ?>
">
</form>
<?php
} else {
// Form was submitted, and validated with no errors. OK to run db insert, display success message, etc.
echo "Successful submission!";
}
?>
</body>
</html>

Link to comment
Share on other sites

No a switch statement is to compare 1 variable... So like lets say we had variables $x,$y,$z

 

the code would go as follows:

switch($x){
case "":
//if $x == "" then do this:
echo 'Its blank';
break;

case "1":
//if $x == "1" then do this:
echo "It says 1";
break;

case "2":
//If $x == "2" then do this:
echo "ITs says 2";
break;
}

 

A switch only allows us to compare variable $x to what ever is in our cases.... So you would need to make 3 different switch statements and then do an If statement anyway to see if they matched what you needed.

Link to comment
Share on other sites

That is truly a bad way of validating data and presenting errors. You should perform ALL validations at the same time, and present ALL error messages to the user, along with redisplaying the form with their previous entries pre-populated in the fields. Here's my stock 'example' form. Paste it in to a new script, and study how it works. It should give you some ideas on form error handling, storing errors in arrays and adding some field styling in response to validation results.

 

<?php
if( isset($_POST['submitted']) && $_POST['submitted'] == 'yes' ) { //check for hidden field value to indicate form has been submitted
$errors = array(); // initialize an array to hold validation errors
$_POST = array_map('trim', $_POST); // trim all $_POST array values

if( !empty($_POST['name']) ) { // validate the name field
	if( !ctype_alpha($_POST['name']) ) {
		$errors['name'][] = 'Name must be alphabetic characters only.'; // if name has non alpha chars, store error
	}
	if( strlen($_POST['name']) < 3 || strlen($_POST['name'] > 20) ) {
		$errors['name'][] = 'Name must be from 3 to 20 characters.'; // if name has too many/few chars, store error
	}
} else {
	$errors['name'][] = 'Name is a required field.'; // if name is empty, store error
}

if( !empty($_POST['number']) ) { // same validations as in name, above.
	if( !ctype_digit($_POST['number']) ) {
		$errors['number'][] = 'Number must be numeric.';
	}
	if( strlen($_POST['number']) < 5 || strlen($_POST['number']) > 10 )  {
		$error = 'Number must be from 3 to 20 digits. It is currently ' . strlen($_POST['number']) . ' digit';
		$error .= strlen($_POST['number']) == 1 ? '.' : 's.';
		$errors['number'][] = $error;
	}
} else {
	$errors['number'][] = 'Number is a required field.';
}
if( !empty($errors) ) {  // if the $errors array is not empty, display the errors to allow the user to correct them and resubmit the form
	$echo = array();
	foreach( $errors as $v ) {
		if( is_array($v) ) {
			$echo[] = implode('<br>', $v );
		} else {
			$echo[] = $v;
		}
	}
	$err_echo ="<font color=\"red\">The following errors were detected:<br>";
	$err_echo .= implode("<br>\n", $echo);
	$err_echo .= '</font>';
}
}
if( (isset($_POST['submitted']) && !empty($errors)) || !isset($_POST['submitted']) ) {
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<style type="text/css" media="screen">
body {
font-family: helvetica, arial, sans-serif;
font-size: 0.85em;
line-height: 1.25em;
letter-spacing: -0.5px;
}
input {
border: 1px solid #336699;
padding: 0.1em;
margin: 5px;
color: #113366;
}
input.error {
background-color: #F2BDCA;
color: #850310;
border: 1px solid red;
}
input.good {
background-color: #D3F5D3;
border: 1px solid #156B15;
color: #156B15;
}
input.submit {
background-color: #CCCCCC;
border: 1px solid #888888;	color: #333333;
padding: 2px;
margin: 0;
font: 0.9em helvetica, arial sans-serif;
}
</style>
<title> Work In Progress</title>
</head>
<body>
<?php
echo !empty($err_echo) ? $err_echo : '';
?>
<form method="post" action="">
Name (3-20 letters):
<input type="text"
class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['name']) ? 'error' : 'good'; } ?>"
name="name"
value="<?php echo isset($_POST['name']) ? $_POST['name'] : ''; ?>">
<br>
Number (5-10 numbers):
<input type="text"
class="<?php if( isset($_POST['submitted']) ) { echo !empty($errors['number']) ? 'error' : 'good'; } ?>"
name="number" value="<?php echo isset($_POST['number']) ? $_POST['number'] : ''; ?>">
<br>
<input type="hidden" name="submitted" value="yes">
<input class="submit" type="submit" name="submit" value="
<?php echo !empty($errors) ? 'Re-Submit' : 'Submit'; ?>
">
</form>
<?php
} else {
// Form was submitted, and validated with no errors. OK to run db insert, display success message, etc.
echo "Successful submission!";
}
?>
</body>
</html>

 

 

is_numeric performs faster results than ctype.. but i guess ctype checks if its purely digits only.

 

 

Link to comment
Share on other sites

Right, is_numeric() will return TRUE for values such as 12E456, 0xFA94BC, decimals/floats etc., so if all that is to be allowed is numeric (0-9) characters, ctype_digit() is appropriate. It's just an example anyhow :)

Link to comment
Share on other sites

I just tried the following code and got no luck. I can't display all the requirements at once because it has to go like a story, it has to be done one at a time.

 

This time, I started the statement as a regular if/else and then nested the switch statement inside the else portion.

 

If the password or email is invalid, echo "please enter a valid email and password"

else

 

switch($password)

 

case $passwordhasnonumber:

         

etc

 

I'm not actually even sure how the switch will work in this case...

 


if( $v_name == "" || $v_msg == "" )

{
	$query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}

	echo <<<EOD
		<head>      
			<link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css">
		</head>
		<h2>Free Registration</h2>
		<form action="contact_insert2.php" method="POST" id="insert">
			<table>
				<tr>
					<td>Email</td>
					<td ><input type="text" size="40" name="name"></td>
				</tr>
			    <tr>
					<td>Password</td>
					<td><input type="password" size="40"  name="msg" ></td>
				</tr>
				<tr>
					<td colspan=2 id="sub">
						You must enter an email and password. <br />
						<input type="submit" name="submit" value="submit">
					</td>
				</tr>
			</Table>
		</form>
EOD;
}
// If it DOES NOT HAVE a number
else {

switch($v_msg)    {
case strcspn( $_REQUEST['msg'], '0123456789' ) == strlen( $_REQUEST['msg'] )
			$query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}	
}
}

Link to comment
Share on other sites

Right, is_numeric() will return TRUE for values such as 12E456, 0xFA94BC, decimals/floats etc., so if all that is to be allowed is numeric (0-9) characters, ctype_digit() is appropriate. It's just an example anyhow :)

 

Cool, you know what, I really love the array_map function, I just came back from a competition in skills and technology, it saved me alot of time, but this is kind of off topic :)

Link to comment
Share on other sites

mgallforever

 

it sounds like your solution is the easiest. In your example, it literally is doing this.

 

if a person enters an invalid password or email, it must say "you must enter a valid email and password"

if there is no number, it must display "you must use at least a number.

if there is no special character, it must display "you must use at least 1 special character"

if there is less than 8 characters, it must display "you must enter at least 8 characters"

if there is no capital letters, it must display "At least one letter must be capitalized"

 

 

I didn't even know you can do if in separate individual statements like you had it.

 

If it doesn't satisfy the condition in the first if, it just moves on to the second one?

Link to comment
Share on other sites

Did you bother to look at or maybe even try the code I posted? It does pretty much the exact same thing.

 

I did, but I'm not very good at PHP, I'm completely new.

 

I don't really understand a lot of what you pasted and I need to customize it (my program has to log everything into the DB even if what the user typed in doesn't satisfy requirements).

 

Also I'm not sure how I would port it over.

 

I guess I could do a "replace all" of your variables to mine, but I really doubt it would work knowing how bad I am with computers.

Link to comment
Share on other sites

Did you bother to look at or maybe even try the code I posted? It does pretty much the exact same thing.

 

this.

 

and i think the OP is wondering how the ORDER of the if/else will work..

 

PHPchick,  If you simply do

 

if($var ==""){

print "please enter the var 1 field" ;

}
if($var2 ==""){

print "please enter the var 2 field";

}

if($var3 ==""){

print "please enter the var 3 field";

}

 

Output

 

Please enter the var 1 field
Please enter the var 2 field
Please enter the var 3 field

 

it will display all 3 errors..

 

although if you do this method

 

if($var == ""){

print "please enter the var 1 field";

}elseif($var2 ==""){
print "please enter the var 2 field";
}

 

Then it will go in sequence. It will run through the entire if/elseif script, and if the one of the conditions are met, it will print that error... It will keep printing 1 error everytime as long as the conditions are met until there are no more errors...

Link to comment
Share on other sites

PHPsensei

 

the OP just sucks at PHP  :-[

 

We all began somewhere, no one is born with ultimate knowledge of PHP.

 

Your doing great btw, don't worry about it. Keep pushing yourself, never stay in your comfort zone, and always set a challenge for yourself in programming and you'll learn over time.

Link to comment
Share on other sites

I basically am doing multiple if statements as individuals.

 

I'm making great progress but I am at the part of the program where I want to make the user add at least one capital letter but it doesn't seem to recognize capital letters as capital letters.

 

I'm typing in GoLamb21

 

but it keeps telling me that "Your password must contain at least one capital letter"

 

It doesn't seem to be recognizing the G?

 

	if( !ctype_lower($_POST['msg']) )
// the above statement says if pass is all lowercase
{
	$query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}
	echo <<<EOD
		<head>      
			<link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css">
		</head>
		<h2>Free Registration</h2>
		<form action="contact_insert2.php" method="POST" id="insert">
			<table>
				<tr>
					<td>Email</td>
					<td ><input type="text" size="40" name="name"></td>
				</tr>
			    <tr>
					<td>Password</td>
					<td><input type="password" size="40"  name="msg" ></td>
				</tr>
				<tr>
					<td colspan=2 id="sub">
						<div style="color:red;">Your password must have at least one capital letter.</div> <br />
						<input type="submit" name="submit" value="submit">
					</td>
				</tr>
			</Table>
		</form>	
EOD;
}

	if( !ctype_alpha($_POST['msg']) )
// the above statement says if pass contains no special characters
{
	$query = "INSERT INTO contact(name,email,msg) VALUES ('$v_name','$v_email','$v_msg')";
	$result = mysql_query( $query );

	if( !$result ) {
		die( mysql_error() );
	}
	echo <<<EOD
		<head>      
			<link rel="stylesheet" type="text/css" href="http://hedgezoo.com/signup.css">
		</head>
		<h2>Free Registration</h2>
		<form action="contact_insert2.php" method="POST" id="insert">
			<table>
				<tr>
					<td>Email</td>
					<td ><input type="text" size="40" name="name"></td>
				</tr>
			    <tr>
					<td>Password</td>
					<td><input type="password" size="40"  name="msg" ></td>
				</tr>
				<tr>
					<td colspan=2 id="sub">
						<div style="color:red;">Your password must have at least one special character.</div> <br />
						<input type="submit" name="submit" value="submit">
					</td>
				</tr>
			</Table>
		</form>	
EOD;
}

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.