tags:

views:

80

answers:

3

Hello,

I am trying to post a form with two fields (name and email) into a MySQL table.

On local server (my laptop), it works just fine.

But on production server, it is posting twice!

I can't figure out why.

Here is the code:

$name = ucwords(strtolower(trim($_POST['name'])));

$email = strtolower(trim($_POST['email']));

$mysqli = new mysqli($server, $serveruser, $serverpass, $dbname);

$name = $mysqli->real_escape_string($name);

$email = $mysqli->real_escape_string($email);

$sql = "INSERT INTO table_name (name, email) VALUES ('" . $name . "', '" . $email . 
"')";

$res = mysqli_query($mysqli, $sql);

It is driving me nuts.

A: 

I think the problem could be at the client side. Maybe your form is posting twice for some reason. As debugging I would do two things:

  1. Make email a PK in the DB just to give an error immediately when the Insert occurs.
  2. Check the query results and post errors (if any)
Freddy
I have a separate PK in the table called "id" with auto increment.
leo
the table's storage engine is MyISAM.
leo
Okay, make email unique then. You want two of the same emails to trigger an error.
Josh Pinter
Hi, if I make email unique, the problem goes away. I'm really really curious what might be the bug. PHP? MySQL? or $mysqli?
leo
Well, the problem don't "goes away". It is there, but you are avoiding it. I think there is a problem with the form or client that is calling the php script. After the insert you should print any sql error, that will be the first step to find your problem.
Freddy
A: 

try $sql = "INSERT ignore INTO table_name (name, email) VALUES ('" . $name . "', '" . $email . "')";

PHPWizard
+1  A: 

I know it sounds like an obvious thing, but, obvious things tend to be the last thing we check for some reason...

Are the files on your laptop and on the server identical? Could it be that you are executing a similar SQL query somewhere else, causing the double-entry?

If you comment out the line which contains (what you think is the only) SQL query, does anything get entered into the database? If so, you do have a second SQL query somewhere else.

Is the file which contains this code being incorporated into another file using the require or include functions? If so, would the require_once or include_once function be a better choice?

Whilst these other fixes may work, they are patches - removing the symptom rather than addressing the cause. Better to sort it out at the deepest level you can find it, rather than just work around this unexpected behaviour.

Lucanos