Jump to content

I'm Using Empty() But Want To Allow '0', And Why No Record Added To Mysql?


wright67uk

Recommended Posts

How can I prevent my if statements echoing a message if the form value in question is '0' ?

 

When a user submits the form, and gets as far as 'A score for $location, has now been added',

 

the code also echo's the users input - everything seems ok, except nothing is added to mysql db.

Is this most likely due to the config of my db, or does something in my PHP stand out?

 

<?php
function sanitize($in) { return addslashes(htmlspecialchars(strip_tags(trim($in)))); }


if(isset($_POST['processForm']))
{
$location = sanitize($_POST['location']);
$sum1 = sanitize($_POST['sum']);
$sum2 = sanitize($_POST['sum2T']);
$sum3 = sanitize($_POST['sum3']);
$sum4 = sanitize($_POST['sum4']);
$sum5 = sanitize($_POST['sum5']);
$sum6 = sanitize($_POST['sum6']);
$sum7 = sanitize($_POST['sum7']);
$sum8 = sanitize($_POST['sum8']);
$sum9 = sanitize($_POST['sum9']);
$totalpar = sanitize($_POST['totalparscore']);

if (empty($sum1)) {echo '<p class="white">You havent entered a score for Hole 1</p>'; exit();}
else if (empty($sum2)) {echo "You haven't entered a score for Hole 2"; exit();}
else if (empty($sum3)) {echo "You haven't entered a score for Hole 3"; exit();}
else if (empty($sum4)) {echo "You haven't entered a score for Hole 4"; exit();}
else if (empty($sum5)) {echo "You haven't entered a score for Hole 5"; exit();}
else if (empty($sum6)) {echo "You haven't entered a score for Hole 6"; exit();}
else if (empty($sum7)) {echo "You haven't entered a score for Hole 7"; exit();}
else if (empty($sum8)) {echo "You haven't entered a score for Hole 8"; exit();}
else if (empty($sum9)) {echo "You haven't entered a score for Hole 9"; exit();}



$user_id = 7;

PASSWORDS
$connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect) or trigger_error(mysql_error(),E_USER_ERROR);
@mysql_select_db($database_connect) or die (mysql_error());

$location = mysql_real_escape_string($location);

$sql = "INSERT INTO snag_scores
(user_id, location, sum1, sum2, sum3, sum4, sum5, sum6, sum7, sum8, sum9, totalpar)
VALUES ('$user_id', '$location', '$sum1', '$sum2' '$sum3', '$sum4', '$sum5', '$sum6', '$sum7', '$sum8', '$sum9', $totalpar)";

mysql_query($sql);

echo "<br/> A score for $location, has now been added.";

};

echo "1:" . $sum1 . "<br/>";
echo "2:" . $sum2 . "<br/>";
echo "3:" . $sum3 . "<br/>";
echo "4:" . $sum4 . "<br/>";
echo "5:" . $sum5 . "<br/>";
echo "6:" . $sum6 . "<br/>";
echo "7:" . $sum7 . "<br/>";
echo "8:" . $sum8 . "<br/>";
echo "9:" . $sum9 . "<br/>";
echo "Total" . $totalpar;

?>

Link to comment
Share on other sites

You should really reconsider your "sanitize" function. But to your problem, you have a validation check that only outputs a message. It then proceeds to try and insert the record anyway! So, you first need to work on the validation to reject anything that does not pass. As to the 0 value, check the manual for empty() - it will return true for empty strings or anything considered false (e.g. 0). So, what SHOULD that validation really be. I think you would want to ensure that value is a positive integer. Is that correct? If so, empty is the wrong type of validation. Is there a maximum value you want to enforce?

Link to comment
Share on other sites

Thanks for the reply I will look into the function. I was under the presumption that the exit: in the if statement would of stopped the insert and that the 'score has now been added' message would only of echoed, if the code had got as far as the sql INSERT but obviously this has proven to be wrong, . The value could be anything from -20 to 20...

Edited by wright67uk
Link to comment
Share on other sites

OK, here is a rewrite of your code in what I consider a more logical flow which will do a correct validation of those values. But, for the sake of efficient code I made a change that requires you to modify your form. Instead fo the fields being named 'sum', 'sum2', 'sum3', etc. you should make them an array. So the names should be like this

Score 1: <input type="text" name="scores[1]" />
Score 2: <input type="text" name="scores[2]" />
Score 3: <input type="text" name="scores[3]" />
. . . 

 

Note: I'm not sure I understand everything about what your expectations are so some processes may not be to your needs

<?php

function sanitize($in)
{
   return htmlspecialchars(strip_tags(trim($in)));
}

function validScore($score)
{
   return (is_int($val) && $score>= -20 && $score <= 20)
}

if(isset($_POST['processForm']))
{
   //Create variable to track errors
   $errors = array();

   //Validate location
   $location = sanitize($_POST['location']);
   if($location=='')
   {
    $errors[] = "You have not provided a valid location";
   }

   //Validate scores for holes 1 - 9 explicitly
   $sums = array_map('trim', $_POST['scores']);
   for($hole_no=1; $hole_no<=9; $hole_no++)
   {
    if(!isset($sum[$hole_no]) || !validScore($sum[$hole_no]))
    {
	    $errors[] = "You haven't entered a valid score for Hole {$hole_no}";
    }
   }

   //Validate total par
   ## ?? Shouldn't this just be calculated based on the score of each hole ??
   $totalpar = trim($_POST['totalparscore']);
   if(!ctype_digit($totalpar)
   {
    $errors[] = "You haven't entered a valid score for Total Par Score";
   }

   //If no validation errors attempt to enter record
   if(!count($errors))
   {
    $connect_solning = mysql_connect($hostname_connect, $username_connect, $password_connect)
	    or trigger_error(mysql_error(),E_USER_ERROR);
    @mysql_select_db($database_connect) or die (mysql_error());

    $user_id = 7;
    $location = mysql_real_escape_string($location);
    $sql = "INSERT INTO snag_scores
			    (user_id, location, sum1, sum2, sum3, sum4,
				 sum5, sum6, sum7, sum8, sum9, totalpar)
		    VALUES
			    ('$user_id', '$location', '$sum[1]', '$sum[2]' '$sum[3]', '$sum[4]',
				 '$sum[5]', '$sum[6]', '$sum[7]', '$sum[8]', '$sum[9]', $totalpar)";
    $result = mysql_query($sql);
    if(!$result)
    {
	    $errors[] = "Error running query: $sql<br>Error:" . mysql_error();
    }
   }

   //Check if record was inserted
   if(!count($errors))
   {
    //Record was added
    echo "<br/> A score for {$location} has now been added.<br>\n";
    foreach($sums as $hole => $score)
    {
	    echo "{$hole}: {$score}<br/>\n";
    }
    echo "Total: {$totalpar}";
   }
   else
   {
    //There were errors - display them
    echo "The following errors occured:\n";
    echo "<ul>\n";
    foreach($errors as $err)
    {
	    echo "<li class=\"white\">{$err}</li>\n";
    }
    echo "<ul>\n";
   }
}

?>

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.