Richard
Richard

Reputation: 6116

PHP Mysql insert only after submit

I have 2 pages. After the user inserts all their info on page 1, they go to page 2. All the inputted information gets correctly stored in $_POST so I can access it in the next page. I can also insert into mysql database just fine no problem. The thing I'm trying to do is to ONLY execute the insert into the database code IF they click the submit button on the second page. I tried doing this:

Page2.php

<script>
$(document).ready(function(e) {
    $("#PaySubmit").click(function() {
        $.ajax({
            url: 'Insert.php'
        });
    });
});
</script>
<input type="submit" name="PaySubmit" id="PaySubmit" value="Continue"/>

Insert.php

try {
    $link = new PDO('mysql:host=****;dbname=****;charset=UTF-8','****','****');
    $first = $_POST["fname"];
    $last = $_POST["lname"];

    $stmt = $link -> prepare("INSERT INTO Conference (`First Name`, `Last Name`) VALUES (:first, :last)");
        $stmt->bindParam(':first', $first);
        $stmt->bindParam(':last', $last);
    $stmt->execute();

} catch(PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

The problem is, when you click submit on the 2nd page $_POST gets replaced with data from the second page, so I no longer have access to the 1st page's data. Any ideas on how to go about this?

Upvotes: 3

Views: 488

Answers (3)

Mahmoud Aladdin
Mahmoud Aladdin

Reputation: 546

I'd suggest you make the DBconnection as a singleton class. And adjust the query once you go to page 2, and execute it, when you click submit in page 2.

Upvotes: 0

Mike Brant
Mike Brant

Reputation: 71384

As an alternative to storing in session, you could simply pass the values from the first page to the second via use of hidden input fields. Something like this:

foreach($_POST as $k => $v) {
?>
<input type="hidden" name="<?php echo $k; ?>" value="<?php echo $v; ?>" />
<?php
}

Of course you may want to sanitize data in post in some manner before posting to next page, but this should give you an idea of what to do.

Upvotes: 0

Zevi Sternlicht
Zevi Sternlicht

Reputation: 5399

Store all the values from the first post in the current SESSION.

You can then access them with the $_SESSION global.

Have a look at the serialize function, it might be able to help you a lot. Or json_encode. They are very useful for storing arrays in one variable and retrieving it later.

Upvotes: 5

Related Questions