写入数据库?

时间:2013-05-07 11:22:02

标签: php mysql database forms validation

我正在尝试编写一些代码,只有在没有验证错误的情况下,才能将输入的数据从表单写入数据库中的表。

我当前的代码不允许我将数据写入数据库,因为它要求填写表单中的每个字段以便能够写入但我只需要表单中的某些字段是强制性的,而不是所有这些都需要。

我实际需要的字段是客户ID,名字和姓氏,我已经为他们编写了以前的工作验证代码。

这是我的代码:

<body>

<?php

/* CUSTOMER ID VALIDATION */

if (isset($_POST["submit"])) {  

$number = $_POST["customerid"];
$msg = "";

if(empty($number)) {
    $msg = '<span class="error"> Please enter a Customer ID</span>';
} else if(!is_numeric($number)) {
    $msg = '<span class="error"> Data entered was not numeric</span>';
} else if(strlen($number) != 6) {
    $msg = '<span class="error"> Customer ID must be 6 digits in length</span>';
} else {
   /* Success */
}

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* FIRST NAME VALIDATION */

if (isset($_POST["submit"])) {

$flag = false;
$badchar = "";
$string = $_POST["customerfname"];
$string = trim($string);
$length = strlen($string);
$strmsg = "";

if ($length == 0) {
$strmsg = '<span class="error"> Please enter your first name</span>';
$flag = true;}
else if ($length > 30) {
$strmsg = '<span class="error"> Can not enter more than 30 characters</span>';
$flag = true;}
else {
for ($i=0; $i<$length;$i++){
    $c = strtolower(substr($string, $i, 1));
    if (strpos("abcdefghijklmnopqrstuvwxyz-", $c) === false){
        $badchar .=$c;
        $flag = true;
    }
}
if ($flag) {
    $strmsg = '<span class="error"> The field contained the following invalid characters: '.$badchar.'</span>';}
}
if (!$flag) {
    $strmsg = '<span class="error"> Correct!</span>';}
}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* LAST NAME VALIDATION*/

if (isset($_POST["submit"])) {

    $flagl = false;
    $badcharl = "";
    $stringl = $_POST["customerlname"];
    $stringl = trim($stringl);
    $lengthl = strlen($stringl);
    $strmsgl = "";

if ($lengthl == 0) {
$strmsgl = '<span class="error"> Please enter your last name</span>';
$flagl = true;}
else if ($lengthl > 30) {
$strmsgl = '<span class="error"> Can not enter more than 30 characters</span>';
$flagl = true;}
else {
for ($il=0; $il<$lengthl;$il++){
    $cl = strtolower(substr($stringl, $il, 1));
    if (strpos("abcdefghijklmnopqrstuvwxyz-", $cl) === false){
        $badcharl .=$cl;
        $flagl = true;
    }
}
if ($flagl) {
    $strmsgl = '<span class="error"> The field contained the following invalid characters: '.$badcharl.'</span>';}
}
if (!$flagl) {
    $strmsgl = '<span class="error"> Correct!</span>';}

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* ADDRESS VALIDATION */

if (isset($_POST["submit"])) {

$valid_states = array( 'ACT', 'NSW', 'NT', 'QLD', 'SA', 'TAS', 'VIC', 'WA' );

if ( isset( $_POST[ 'customeraddress' ] ) && ! empty( $_POST[ 'customeraddress' ] ) ) {
if ( ! isset( $_POST[ 'state' ] ) || ! in_array( $_POST[ 'state' ], $valid_states ) ) {
    echo "There was an error: the address is set but the state is not.";
}
}

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* POSTCODE VALIDATION */

if (isset($_POST["submit"])) {

$post = $_POST["postcode"];
$msgp = "";

if (!empty($post)) {
if(!is_numeric($post)) {
$msgp = '<span class="error"> Data entered was not numeric</span>';
} else if(strlen($post) != 4) {
$msgp = '<span class="error"> Postcode must be 4 digits in length</span>';
} else {
$msgp = '<span class="error> right</span>';
}

}

}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////

/* WRITE TO DATABASE */

if (isset($_POST["submit"])) {

$conn = mysqli_connect("localhost", "twa312", "dam6av9a");
mysqli_select_db("warehouse312", $conn)
or die ('Database not found ' . mysqli_error() );

$sql = "INSERT INTO customer (customerID, firstName, lastName, address, suburb, state, postcode)
VALUES
('$_POST[customerid]','$_POST[customerfname]','$_POST[customerlname]','$_POST[customeraddress]','$_POST[suburb]','$_POST[state]','$_POST[postcode]')";
$rs = mysqli_query($sql, $conn)
or die ('Problem with query' . mysqli_error());

if (!mysqli_query($conn, $sql))
{
die('Error: ' . mysqli_error($conn));
}
echo "1 record added";

mysqli_close($conn);

}

?>

<h1>Customer Information Collection <br /></h1>

<form method="POST" action="<?php echo $_SERVER["PHP_SELF"];?>" id="custinfo" >
<table>
<tr>
    <td><label for="customerid">Customer ID (integer value): </label></td>
    <td><input type="text" id="customerid" name="customerid" value="<?php echo $temp ?>" size=11 /><?php echo $msg; ?></td>
</tr>

<tr>
    <td><label for="customerfname">Customer First Name: </label></td>
    <td><input type="text" id="customerfname" name="customerfname" size=50/><?php echo $strmsg; ?></td>
</tr>
<tr>
    <td><label for="customerlname">Customer Last Name: </label></td>
    <td><input type="text" id="customerlname" name="customerlname" size=50/><?php echo $strmsgl; ?></td>
</tr>
<tr>
    <td><label for="customeraddress">Customer Address: </label></td>
    <td><input type="text" id="customeraddress" name="customeraddress" size=65/></td>

    <td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td>
State:<select name="state" id="state">
    <option value="select">--</option>
    <option value="ACT">ACT</option>
    <option value="NSW">NSW</option>
    <option value="NT">NT</option>
    <option value="QLD">QLD</option>
    <option value="SA">SA</option>
    <option value="TAS">TAS</option>
    <option value="VIC">VIC</option>
     <option value="WA">WA</option>
  </select>
</td>
<td><label for="postcode"> Post Code: </label><input type="text" id="postcode" name="postcode" size=4/><?php echo $msgp; ?></td>
</tr>
</table>
<p><input type="submit" name="submit" value="Save Data"/>&nbsp;<input type="reset" value="Clear Form" />
</tr>

</form>

</body>

对此解决方案的任何帮助都表示赞赏!

4 个答案:

答案 0 :(得分:2)

基本方法应该是这样的。在顶部,设置一个变量:

$valid = true;

然后在执行每个验证检查时,如果失败,则设置:

$valid = false;

除了向用户打印错误消息外。

最后,在完成所有验证后,您可以:

if ($valid) {
    // Code to add to database
}

要允许可选字段,您可以执行以下操作:

if (isset($_POST['postcode'])) {
    $post = $_POST['postcode'];
    // validation of field
} else {
    $post = '';
}

为所有其他可选字段添加else子句,将变量设置为默认值。

答案 1 :(得分:1)

虽然您的实施几乎没问题,但问题是您每次都在检查

 if(isset($_POST['submit']))

这是错误的,只需检查单个

中的所有验证
if(isset($_POST['submit'])) {

     //your id validation
     //your first name validation
     //your last name validation

     if (youhavenoerror) {
         //perform sql operation
     }

}

答案 2 :(得分:0)

这段代码可以改进很多。

但是现在对你的问题的简短回答是在你的代码之上将变量标志设置为true。然后在进行验证时如果验证失败,则将该标志设置为false。稍后插入db时,检查此标志是否为true,否则不插入。

答案 3 :(得分:0)

您必须逐步完成。在分析和逐行学习之前复制代码。

试试这样。但这不是编码的最佳实践。我刚刚编辑了您的代码以供您理解..

<body>
<?php
/* CUSTOMER ID VALIDATION */
if (isset($_POST["submit"]))
{
    $flag = false;

    $number = $_POST["customerid"];
    $msg = "";

    if (empty($number))
    {
        $msg = '<span class="error"> Please enter a Customer ID</span>';
        $flag = true;
    } else
        if (!is_numeric($number))
        {
            $msg = '<span class="error"> Data entered was not numeric</span>';
            $flag = true;
        } else
            if (strlen($number) != 6)
            {
                $msg = '<span class="error"> Customer ID must be 6 digits in length</span>';
                $flag = true;
            } else
            {
                /* Success */
            }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /* FIRST NAME VALIDATION */
    $badchar = "";
    $string = $_POST["customerfname"];
    $string = trim($string);
    $length = strlen($string);
    $strmsg = "";

    if ($length == 0)
    {
        $strmsg = '<span class="error"> Please enter your first name</span>';
        $flag = true;
    } else
        if ($length > 30)
        {
            $strmsg = '<span class="error"> Can not enter more than 30 characters</span>';
            $flag = true;
        } else
        {
            for ($i = 0; $i < $length; $i++)
            {
                $c = strtolower(substr($string, $i, 1));
                if (strpos("abcdefghijklmnopqrstuvwxyz-", $c) === false)
                {
                    $badchar .= $c;
                    $flag = true;
                }
            }
            if ($flag)
            {
                $strmsg = '<span class="error"> The field contained the following invalid characters: ' . $badchar .
                    '</span>';
            }
        }
        if (!$flag)
        {
            $strmsg = '<span class="error"> Correct!</span>';
        }

    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /* LAST NAME VALIDATION*/
    $badcharl = "";
    $stringl = $_POST["customerlname"];
    $stringl = trim($stringl);
    $lengthl = strlen($stringl);
    $strmsgl = "";

    if ($lengthl == 0)
    {
        $strmsgl = '<span class="error"> Please enter your last name</span>';
        $flag = true;
    } else
        if ($lengthl > 30)
        {
            $strmsgl = '<span class="error"> Can not enter more than 30 characters</span>';
            $flag = true;
        } else
        {
            for ($il = 0; $il < $lengthl; $il++)
            {
                $cl = strtolower(substr($stringl, $il, 1));
                if (strpos("abcdefghijklmnopqrstuvwxyz-", $cl) === false)
                {
                    $badcharl .= $cl;
                    $flag = true;
                }
            }
            if ($flag)
            {
                $strmsgl = '<span class="error"> The field contained the following invalid characters: ' . $badcharl .
                    '</span>';
            }
        }
        if (!$flag)
        {
            $strmsgl = '<span class="error"> Correct!</span>';
        }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /* ADDRESS VALIDATION */
    $valid_states = array(
        'ACT',
        'NSW',
        'NT',
        'QLD',
        'SA',
        'TAS',
        'VIC',
        'WA');

    if (isset($_POST['customeraddress']) && !empty($_POST['customeraddress']))
    {
        if (!isset($_POST['state']) || !in_array($_POST['state'], $valid_states))
        {
            echo "There was an error: the address is set but the state is not.";
            $flag = true;
        }
    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /* POSTCODE VALIDATION */

    $post = $_POST["postcode"];
    $msgp = "";

    if (!empty($post))
    {
        if (!is_numeric($post))
        {
            $msgp = '<span class="error"> Data entered was not numeric</span>';
            $flag = true;
        } else
            if (strlen($post) != 4)
            {
                $msgp = '<span class="error"> Postcode must be 4 digits in length</span>';
                $flag = true;
            } else
            {
                $msgp = '<span class="error> right</span>';
            }

    }

    if (!$flag)
    {
        $conn = mysqli_connect("localhost", "twa312", "dam6av9a");
        mysqli_select_db("warehouse312", $conn) or die('Database not found ' . mysqli_error());

        $sql = "INSERT INTO customer (customerID, firstName, lastName, address, suburb, state, postcode)
VALUES
('$_POST[customerid]','$_POST[customerfname]','$_POST[customerlname]','$_POST[customeraddress]','$_POST[suburb]','$_POST[state]','$_POST[postcode]')";
        $rs = mysqli_query($sql, $conn) or die('Problem with query' . mysqli_error());

        if (!mysqli_query($conn, $sql))
        {
            die('Error: ' . mysqli_error($conn));
        }
        echo "1 record added";

        mysqli_close($conn);
    }

}

?>

<h1>Customer Information Collection <br /></h1>

<form method="POST" action="<?php

echo $_SERVER["PHP_SELF"];

?>" id="custinfo" >
<table>
<tr>
    <td><label for="customerid">Customer ID (integer value): </label></td>
    <td><input type="text" id="customerid" name="customerid" value="<?php

echo $temp

?>" size=11 /><?php

echo $msg;

?></td>
</tr>

<tr>
    <td><label for="customerfname">Customer First Name: </label></td>
    <td><input type="text" id="customerfname" name="customerfname" size=50/><?php

echo $strmsg;

?></td>
</tr>
<tr>
    <td><label for="customerlname">Customer Last Name: </label></td>
    <td><input type="text" id="customerlname" name="customerlname" size=50/><?php

echo $strmsgl;

?></td>
</tr>
<tr>
    <td><label for="customeraddress">Customer Address: </label></td>
    <td><input type="text" id="customeraddress" name="customeraddress" size=65/></td>

    <td><label for="suburb"> Suburb: </label></td>
<td><input type="text" id="suburb" name="suburb"/></td>
</tr>
<tr>
<td>
State:<select name="state" id="state">
    <option value="select">--</option>
    <option value="ACT">ACT</option>
    <option value="NSW">NSW</option>
    <option value="NT">NT</option>
    <option value="QLD">QLD</option>
    <option value="SA">SA</option>
    <option value="TAS">TAS</option>
    <option value="VIC">VIC</option>
     <option value="WA">WA</option>
  </select>
</td>
<td><label for="postcode"> Post Code: </label><input type="text" id="postcode" name="postcode" size=4/><?php

echo $msgp;

?></td>
</tr>
</table>
<p><input type="submit" name="submit" value="Save Data"/>&nbsp;<input type="reset" value="Clear Form" />
</tr>

</form>

</body>