How to access the last record in a database table using PHP


I’m making a very simple form in PHP. It has three fields ‘name’, ‘email’ and ‘comment’. Upon form submission these fields get written to a database table.

So as to prevent double data submission I’m trying to do the following: when a user clicks send, I look up the previous record in the database and compare the comment field of that record with the comment field of the data that is being submitted. If they are the same, then I would discard the submission.

Two questions:
a) How would I go about getting the comment field from the previously submitted record into a variable within my PHP script?

So far I have:

$query = "SELECT * FROM guestbook ORDER BY id DESC limit 0,1";
$last = mysql_query($query);

which (I think) gets me the previous record. But how can I access the field ‘comment’ from within this record. ($last.comment would work in rails).

b) Is this a good / sensible way to stop double data submission in a simple form.

Thanks in advance

You could store a hash (md5, sha1 et al) of the last comment made by that user in their $_SESSION, this would prevent them submitting the same comment twice.

I’d also use something unique to the subject matter that they are commenting on too, just in case they want to add “I agree” to more than one commentable item.

Something like…

$_SESSION['last_comment_hash'] = md5($post_id . $_POST['comment']);

This would prevent the round trip to the database. Additionally, take a look at Post, Redirect, Get pattern.

If you are worried about users clicking the submit button twice in rapid succession, I would just disable the submit button with javascript once it’s clicked.

Beware, do not do this in the onsubmit of the form. If you do IE won’t submit anymore, at all. Instead put it in the onclick of the submit button.

If you’re using jQuery it would be:

$('input[type="submit"]').click( function() { $(this).attr('disabled','disabled'); } );

If you are worried people might reload the page and resubmit the data, look at post-refresh-get like Anthony just said :slight_smile:

UNIQUE index would be helpful.

Thank you all for the answers. They were very helpful.
I didn’t know about the Post, Redirect, Get pattern, so reading about that was very interesting.
On reflection, this is a small, temporary site for family and friends, so it is perfectly adequate to use JavaScript to disable the send button.
I have read a bit about that now and have a couple of questions, but I’ll head over to the JavaScript forum and post them there.