开发者

Unfilled form values creating empty rows in mysql via php

First time poster, long time lurker :) I have a form setup that posts data for multiple 开发者_JAVA百科rows in a single table with seven colums to a php function to insert it as new records in a database. The form is working great, however, if one of the rows in the form is left unfilled then the php function is creating a blank row in the database. I am attempting to figure out how to avoid this. I am certain it has nothing to do with the form itself, and rather has to do with the php. Please have a look at it. I'm totally open to suggestions.

<?php
require("header.php");
require("dbinc.php");
foreach($_POST['card'] as $row=>$cardcounted) 
{
    $model=$_POST['model'];
    $serial=$_POST['serial'][$row];
    $card=$cardcounted;
    $status=$_POST['status'];
    $date=$_POST['date'];
    $location=$_POST['location'];
    $query = mysql_query("INSERT INTO receivers (`id`, `model`, `serial`, `card`, `status`, `date`, `location`) VALUES ('null','$model','$serial','$card','$status','$date','$location')");

    if(!isset($serial[$row]) || $serial[$row] == '') {
        // error message here, redisplay form if desired
    } else {
        // no errors - process data
    } 

    if (!$query)
    {
        die('Error: ' . mysql_error());
    }
}
echo $row+1 . " record(s) added";

mysql_close()
?>

I added in the !isset on the serial numbers by row to check for null posts but am unsure as to how to incorporate that properly. i think im on the right track, just need that little push :)


First choice is to use JavaScript validation to find out invalid form submits, Some users may disable JavaScript, so its always recommended to do server-side validations

So write a method like

isValid($postArray) {
  foreach($postArray as $key => $value) {
    if ($value == "") {
       return false;    
    }
  }
  return true;
}

If form field names and db column names are similar you can use

$sql = "INSERT INTO receivers ";
$keys = "(";
$values = "(";
foreach($postArray as $key => $value) {
    if ($value != "") {
       $keys += $key;
       $values += $value;
    }
}

$sql = $sql + $keys +" VALUES "+ $values;


Maybe try moving your mysql query into your else currently you insert values into the database regardless of whether you have form errors or not. Also you will need to secure anything that you are inserting into your database. Its an SQL injection field trip right now ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜