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 preve开发者_如何学编程nt empty input submit before form submit or after submit so it can send me back to form.php
.
Thank you.
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;
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.
You can check whether the input value was filled with:
<?php
if(!empty($_POST['url'])){
// Do something
}
?>
$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
- http://xkcd.com/327/
精彩评论