验证表单然后使用php提交到数据库

验证表单然后使用php提交到数据库

问题描述:

I've been reluctant to come back to * to ask this question. It's definitely been asked many times over, but every answer hasn't been able to fix the problem. I've attempted the Header() fix: https://*.com/a/18820079/3831297 to no avail and now I have been trying to instead just validate and submit from the same page.

When I was using the Header redirect nothing would happen, no redirect to the next page while also not giving any errors for a reason. Which leaves me with the method below.. A mess of code that I've spent 60+ hours on trying to get to work from answers found on here as well as other websites.

What I've been trying to do with this version is validate with:

 if(empty()) {
   display error 
 }else{
   variable = true

 if(variable = true){ 
  post to database
 }

I apologize for the repeated question as well as for my complete lack of knowledge. I am learning as I go with these hands-on projects.

<?php
    if (mysqli_connect_errno()) {
    echo "Connection to the database failed! Submitting a story will not work! Try again in a few minutes!" . mysqli_connect_error();
    }else{
        echo "<br>";
        echo "<h4>" . "Database connected successfully... It is safe to submit a story!" . "</h4>";
}
$TitleErr = $StoryErr = $AuthorErr = $DateErr = "";
$Title = $Story = $Author = $Date = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["Title"])) {
        $TitleErr = "Title is required!";
    }else{
        $valid1 == true;
        }
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["Story"])) {
        $StoryErr = "Story is required!";
    }else{
        $valid2 == true;
        }
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if (empty($_POST["Author"])) {
        $AuthorErr = "Author is required!";

    }else{
        $valid3 == true;
        }
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if(empty($_POST["Date"])) {
        $DateErr = "Date is required!";

    }else{
        $valid4 == true;
        }
}
if ($valid1 = $valid2 = $valid3 = $valid4 = true) {
    $Title = mysqli_real_escape_string($con, $_POST['Title']);
    $Date = mysqli_real_escape_string($con, $_POST['Date']);
    $Author = mysqli_real_escape_string($con, $_POST['Author']);
    $Story = mysqli_real_escape_string($con, $_POST['Story']);

    $sql="INSERT INTO Moderate (Title, Story, Author, Date)
    VALUES ('$Title', '$Story', '$Author', '$Date')";
    if (!mysqli_query($con,$sql)) {
        die('Error: ' . mysqli_error($con));
        }else{
            echo "<br>";
            echo "Story submitted for moderation!";
            }
}


mysqli_close($con);

//Insert into database
//$sql="INSERT INTO Moderate (Title, Story, Author, Date)
//VALUES ('$Title', '$Story', '$Author', '$Date')";
?>
        <h2>Submit News</h2>
        <?php// echo htmlspecialchars($_SERVER["PHP_SELF"]);?>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post">
<span class="error">* <?php echo $TitleErr;?></span>
Title: <input type="text" name="Title">
<span class="error">* <?php echo $AuthorErr;?></span>
Author: <input type="text" name="Author">
<span class="error">* <?php echo $DateErr;?></span>
Date: <input type="date" name="Date">
<input type="submit"><br>

<span class="error">* <?php echo $StoryErr;?></span>
Story: <br><textarea type="textarea" rows="40" cols="100" name="Story" method="post"></textarea>
</form>
</div>
<?php

//// escape variables for security
//$Title = mysqli_real_escape_string($con, $_POST['Title']);
//$Story = mysqli_real_escape_string($con, $_POST['Story']);
//$Author = mysqli_real_escape_string($con, $_POST['Author']);
//$Date = mysqli_real_escape_string($con, $_POST['Date']);

//Insert into database


?>

I'm going to hazard an answer. Main thing I see is you are using == as assignment and = as comparison. This is backwards.

$valid4 == true; should be $valid4 = true;

if ($valid1 = $valid2 = $valid3 = $valid4 = true) should be if ($valid1 == $valid2 == $valid3 == $valid4 == true) or not really, since it actually has to be:

if ($valid1==true && $valid2==true && $valid3==true && $valid4==true)

With assignment you can stack up the operator, but with boolean comparison, combine the compares with and (&&).

Just some advise, don't make pages submit to themselves. Make a separate page to handle the form from the one that displays the form. That way if you ever want to upgrade to using Ajax, its much easier. Also after doing a db update like this you always need to redirect to another page to prevent double submit (unless using ajax). The page doing the db update should not print anything out but just do the db update and redirect, unless there's a validation error.

Change your PHP to this:

if (isset($_POST['Title'],$_POST['Date'], $_POST['Author'], $_POST['Story'] )){

    $con = mysqli_connect("localhost", "my_user", "my_password", "db");

    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s
", mysqli_connect_error());
        exit();
    }

    $title = $_POST['Title'];
    $date = $_POST['Date'];
    $author = $_POST['Author'];
    $story = $_POST['Story'];

    $query = "INSERT INTO Moderate (Title, Story, Author, Date) 
              VALUES (?, ?, ?, ?)"    

    /* create a prepared statement */
    if ($stmt = mysqli_prepare($con, $query)) {
        /* bind parameters for markers */
        mysqli_stmt_bind_param($stmt, "ssss", $city);    
        /* execute query */
        mysqli_stmt_execute($stmt);  
        /* close statement */
        mysqli_stmt_close($stmt);
    }   
    /* close connection */
    mysqli_close($con);
}