0

Page creating database entry when it reloads or when you go to it when using a mysql query. I have it set up so when you hit submit it inserts the data into the database but for some reason on a page reload or even when you go to it, it creates yet another database entry without hitting submit.

<?php

    $con = mysql_connect("xxx","xxxx_user","xxx");
    if (!$con)
      {
die('Could not connect: ' . mysql_error());
  }

mysql_select_db("jjlliinn_test", $con);

$date = $_POST['date'];
$propertydescription = $_POST['propertydescription'];
$transactiontype = $_POST['transactiontype'];
$applicabledocument = "null";
$received = $_POST['received'];
$paid = $_POST['paid'];

$sql = mysql_query("INSERT INTO `transactions` (`date`, `agentclient`, `propertydescription`, `transactiontype`, `applicabledocument`, `received`, `paid`) 
VALUES
 ('$date', '$agentclient', '$propertydescription', '$transactiontype', '$applicabledocument', '$received', '$paid')") or die(mysql_error()); 
$query = mysql_query($sql);


mysql_close($con);
    ?>
A.R
  • 137
  • 1
  • 12

2 Answers2

1

The reason why this happens when you first load the page is you don't check to see if a form has been submitted. You just automatically insert into the database.

To fix this you need to check for a form submission. Assuming you are using POST you could wrap the above code in an if statement that checks to see if this is a form submission and, if so, process the data:

if ('POST' === $_SERVER['REQUEST_METHOD'])
{
    // your code goes here
}

The reason why it happens when someone refreshes the page is because of above, and you also don't do anything to prevent the browser from resubmitting the form data again which they typically do when that is how the page is requested. Look into the POST/REDIRECT/GET pattern to solve this.

Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial. You also wide open to SQL injections

Zoe
  • 27,060
  • 21
  • 118
  • 148
John Conde
  • 217,595
  • 99
  • 455
  • 496
  • Yea I know what you mean about sql injections but this is just a minor script not going to be used for anything big. – A.R Jun 04 '13 at 02:32
0

I bet your code is inside HTML <form></form> tags. Refreshing/Reloading the page browser triggers the form to SUBMIT again.

I suggest that after the mysql_close($con);, use header() and redirect to the same page.

Take a look at this question.

Community
  • 1
  • 1
KaeL
  • 3,639
  • 2
  • 28
  • 56