doesn't insert if a field is blank

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
ultraloveninja
Forum Newbie
Posts: 1
Joined: Tue May 05, 2009 9:33 am

doesn't insert if a field is blank

Post by ultraloveninja »

I forgot how to do this, but I don't want it to insert a record if a field is blank.
Every time I try to do what I think is correct, it makes the form disappear.

Here's what I have:

Code: Select all

 
<?php
if ($_POST['pick'] == "") {
    $msg = "You need to enter a pick.";
    }
if ($_POST) {
$msg="";
include 'dbconn.php';
$enddate=$_POST['enddate'];
$endDateTmp=strtotime($enddate);
$sqldate=strftime('%Y-%m-%d',$endDateTmp);
$insert = "insert ignore into testpick (pick,expiretime,expiredate,starttime) values ('$_POST[pick]','$_POST[endtime]','$sqldate','$_POST[starttime]')";
print $insert;
mysql_query($insert)
 or die(mysql_error());
    $msg = "You have created a new pick.";
    }
    else 
    { 
    $msg = "There was an error inserting the pick.";
    }
//print if it failed or not
echo "<div class=\"error\">$msg</div>";
?>
 
Is that right?
Last edited by Benjamin on Tue May 05, 2009 1:19 pm, edited 1 time in total.
Reason: Changed code type from text to php.
User avatar
infolock
DevNet Resident
Posts: 1708
Joined: Wed Sep 25, 2002 7:47 pm

Re: doesn't insert if a field is blank

Post by infolock »

A little easier solution:

Code: Select all

 
unset($_POST['submit']); // assumes you named a submit button "submit"
$errors = false;
foreach($_POST as $key => $value) {
  if(empty($value)) {
    echo "$key was found to be blank... Cannot insert<br />";
    $errors = true;
  }
}
 
if($errors === true) exit;
 
Post Reply