Reham Fahmy
Reham Fahmy

Reputation: 5073

Stop Submit With Empty Input Values Using PHP

I'm looking for a simple PHP solution to stop empty input values at form from submitting empty input fields. The code for the form is below. I would like to use a simple PHP (non-Javascript) solution if possible.

Form.php code:

<form name="form" method="post" action="add.php">
<input type="text" name="url" id="url">
<button type="submit" id="submit">submit</button>
</form>

add.php code:

$url=$_POST['url'];
$sql= "insert into my_table set url='$url'";
mysql_query($sql) or die("query failed: $sql".mysql_error());
$msg= 'URL Added Thank You';
session_register('msg');
header("Location: form.php ");
exit;

If there any PHP solution to prevent empty input submit before form submit or after submit so it can send me back to form.php.

Thank you.

Upvotes: 1

Views: 14399

Answers (4)

Dan
Dan

Reputation: 594

Personally, I almost always do these things in two steps. Sanitize first, then validate.

// Step 1: Sanitize fields
$url = mysql_real_escape_string($_POST['url']);

// Step 2: Validate fields
if(empty($url))
{
    $msg = "Text can't be empty";
    session_register('msg');
    header("Location: form.php ")
}

// Step 3: Whatever
$sql= "insert into my_table set url='$url'";
mysql_query($sql) or die("query failed: $sql".mysql_error());
$msg= 'URL Added Thank You';
session_register('msg');
header("Location: form.php ");
exit;

Upvotes: 5

Jesse Bunch
Jesse Bunch

Reputation: 6679

Use the empty function:

if (empty($_POST['query'])) {

    // Set error and return to form

}

I would highly suggest also reading up on mysql_real_escape_string.

Upvotes: 2

Phill Pafford
Phill Pafford

Reputation: 85378

$url=$_POST['url'];

if(empty($url)) {
    // redirect back to form
    header("Location: form.php ");
} else {
    // add record
    $sql= "insert into my_table set url='$url'";
    mysql_query($sql) or die("query failed: $sql".mysql_error());
    $msg= 'URL Added Thank You';
    session_register('msg');
    header("Location: form.php ");
    exit;
}

Little Bobby Tables

Upvotes: 1

Bas Slagter
Bas Slagter

Reputation: 9929

You can check whether the input value was filled with:

<?php
  if(!empty($_POST['url'])){
    // Do something 
  }
?>

Upvotes: 1

Related Questions