通过php post js validation提交到mysql

时间:2013-03-26 23:26:12

标签: java php html mysql validation

我正在尝试从html表单向mysql提交数据,但是在我这样做之前,我想使用一些javascript来验证用户输入。当用户单击提交时,js验证工作正常,并且调用php文件,但是当向数据库提交数据时,字段都是空的。这是我现在拥有的:

HTML表单

<form action="StudentSubmit.php" action="validating()" method="post" class="fancy-form">
.
.
<div>
     <div class="fieldgroup">
          <em>*</em><input type="text" name="addressline1" id="addressline1" class="required" minlength="7">
          <label for="addressline1">Street #1</label>
     </div>
</div>
.
.
.
<div class="submit-wrap">
     <button type="submit" class="submit">Submit</button>
</div>

JS

checkdata =
    {
        checkNull: function(textboxval) {
            if ($(textboxval).val() == null || $(textboxval).val() == "") {
                return false;
            }
            else {
                return true;
            }
        },
        checkNumeric: function(textboxval) {
            var value = $(textboxval).val();
            if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
                return true;
            } else {
                return false;
            }
        },
        checkEmail: function(textboxval) {
            var x = $(textboxval).val();
            var atpos = x.indexOf("@");
            var dotpos = x.lastIndexOf(".");
            if (atpos < 1 || dotpos < atpos + 2 || dotpos + 2 >= x.length)
            {
                return false;
            }
        },
        isChecked: function(textboxval) {
            if ($(textboxval).is(':checked') == false)
            {
                return false;
            } else {
                return true;
            }
        }
    };

function validating() {
var returnValue = true;


var boxFields = new Array();
boxFields[0] = "#firstname";
boxFields[1] = "#lastname";
boxFields[2] = "#addressline1";
boxFields[3] = "#homephone";
boxFields[4] = "#cellphone";
boxFields[5] = "#city";
boxFields[6] = "#state";
boxFields[7] = "#guardian";
boxFields[8] = "#zip";
boxFields[9] = "#emergencycontactperson";
boxFields[10] = "#emergencycontactphone";

var nullValue = true;
for (var i = 0; i < boxFields.length; i++) {
    if (checkdata.checkNull(boxFields[i]) == false) {
        nullValue = false;
        break;
    }

}

var numFields = new Array();
numFields[0] = "#homephone";
numFields[1] = "#cellphone";
numFields[2] = "#emergencycontactphone";

var numericValue = true;
for (var j = 0; j < numFields.length; j++) {
    if (checkdata.checkNumeric(numFields[j]) == false) {
        numericValue = false;
        break;
    }

}

var checkFields = new Array();
checkFields[0] = "#signature";

var checkValue = true;
for (var k = 0; k < checkFields.length; k++) {
    if (checkdata.isChecked(checkFields[k]) == false) {
        checkValue = false;
        break;
    }

}

if (nullValue == false || numericValue == false || checkValue == false) {
    returnValue = false;
    alert("Some required fields were left empty");
    return false;
} else {
    return true;
}
}

PHP

<?php
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$dob = $_POST['dob'];
$emergencycontact = $_POST['emergencycontactperson'];
$address = $_POST['addressline1'] . " " . $_POST['addressline2'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip = $_POST['zip'];
$homephone = $_POST['homephone'];
$cellphone = $_POST['cellphone'];
$guardian = $_POST['guardian'];
$inneighborhood = 0;
if ($zip == "49503")
    $inneighborhood = 1;

$con = mysqli_connect("localhost", "cookarts_root", "password_here", "cookarts_database");

// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$sql = "INSERT INTO student (FirstName, LastName, DOB, EmergencyContact, Address, City,       State, ZIP, CellPhone, HomePhone, Guardian, InNeighborhood)
VALUES
   ('$firstname', '$lastname', '$dob', '$emergencycontact', '$address', '$city', '$state',   '$zip', '$cellphone', '$homephone', '$guardian', '$inneighborhood')";

if ($con->query($sql) === TRUE) {
  header( 'Location: http://cookartscenter.net/ThankYou.php' ) ;
}   
else {
  echo 'Error: '. $con->error;
}

mysqli_close($con);
?>

只是为了清除,连接到DB没有问题,我的问题是在JS验证php没有正确地从表单中提取数据之后。如果您需要更多我的HTML代码,我很乐意提供它。感谢。

2 个答案:

答案 0 :(得分:2)

更改

<form action="StudentSubmit.php" action="validating()" method="post" class="fancy-form">

<form action="StudentSubmit.php" method="post" class="fancy-form">

并添加以下内容:

$('form').submit(function ()
{

  if (!validating())
  {
    return false;
  }

}
)

答案 1 :(得分:0)

您正在使用javascript替换初始表单标记中的表单操作。如果设置了两个属性,则最后一个设置属性将是使用的属性。您可以在按钮或onsubmit()上使用onclick()。

<form action="StudentSubmit.php" onsubmit="validating()" method="post" class="fancy-form">

Javascript验证仅适用于使用浏览器的用户。它不适用于垃圾箱或关闭垃圾箱的人。最好的办法是在服务器端使用PHP验证,然后在将输入注入数据库之前清理它们。

同时检查变量以确保它们不是空的:

if(!empty(strip_tags($_POST['firstname']))){
 $firstname = strip_tags($_POST['firstname']);
}

$firstname = $mysqli->real_escape_string($firstname);

您也可以引用PDO连接

$conn->quote($firstname)