从php表格&amp ;;在postgresql数据库中引入数据以

时间:2016-03-11 03:45:17

标签: php database postgresql validation

我有一个来自介绍数据,我试图验证数据。但是,无论是否引入数据,都会在数据库中引入信息。

例如,如果我将名称留空,则会收到一条错误消息,指出该名称不能为空,但会在数据库中引入空白名称。

我该怎么做,所以只有在所有字段都经过验证后,才会在数据库中引入数据?

非常感谢

CODE

<!DOCTYPE HTML>
<html>
<head>
<style>
.error {color: #FF0000;}
</style>
</head>
<body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $surnameErr = "";
$name = $email = $surname = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["name"])) {
 $nameErr = "Name is required";
} else {
 $name = test_input($_POST["name"]);
}

if (empty($_POST["email"])) {
 $emailErr = "Email is required";
} else {
  $email = test_input($_POST["email"]);
}

if (empty($_POST["surname"])) {
  $surname = "";
} else {
 $surname = test_input($_POST["surname"]);
}
}

function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

<h2>PHP Form Validation Example</h2>
<p><span class="error">* required field.</span></p>
<form method="post" action="<?php echo        htmlspecialchars($_SERVER["PHP_SELF"]);?>">
Name: <input type="text" name="name">
<span class="error">* <?php echo $nameErr;?></span>
<br><br>
Last Name: <input type="text" name="surname">
<span class="error"><?php echo $surnameErr;?></span>
<br><br>
E-mail: <input type="text" name="email">
<span class="error">* <?php echo $emailErr;?></span>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
echo "<h2>Your Input:</h2>";
echo $name;
echo "<br>";
echo $email;
echo "<br>";
echo $surname;
echo "<br>";
?>


<?php
   $db = pg_connect('host=localhost dbname=postgres user=myusername password=mypassword');

    $firstname = pg_escape_string($_POST['name']);
    $surname = pg_escape_string($_POST['website']);
    $emailaddress = pg_escape_string($_POST['email']);

    $query = "INSERT INTO friends(firstname, surname, emailaddress)     VALUES('" . $firstname . "', '" . $surname . "', '" . $emailaddress . "')";
    $result = pg_query($db, $query);
    if (!$result) {
        $errormessage = pg_last_error();
        echo "Error with query: " . $errormessage;
        exit();
    }
    printf ("These values were inserted into the database - %s %s %s", $firstname, $surname, $emailaddress);
    pg_close();
    ?>

</body>
</html>

0 个答案:

没有答案