0

when the info is successfully inserted, it's displaying the error message and saying that it's a duplicate entry for a primary key...I can't figure out why!

<?
$email=$_POST['email'];
$pw=$_POST['pw'];

mysql_connect('***','***','***');
@mysql_select_db('***') or die('Unable to select database');

$query = "INSERT INTO test_table VALUES ('','$email','$pw')";
mysql_query($query) or die(mysql_error());

if(mysql_query($query))
{
    echo 'success';
}
else
{
    echo 'failure' .mysql_error();
}

mysql_close();
?>
Dan w
  • 151
  • 1
  • 3
  • 15
  • 3
    [Please, don't use `mysql_*` functions](http://stackoverflow.com/q/12859942/1190388) in new code. They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). See the red box? Learn about prepared statements instead, and use [tag:PDO] or [tag:MySQLi]. – hjpotter92 May 28 '13 at 01:55

4 Answers4

6

You are executing the query twice: first, in mysql_query($query) or die(mysql_error()); and second, in if(mysql_query($query)). So the second time the query executes the record is already there and thus the insertion fails.

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
heap underrun
  • 1,846
  • 1
  • 18
  • 22
2

You are executing same query twice.

$query_result = mysql_query($query) or die(mysql_error());
if ($query_result) {
    echo 'success';
} else {
    echo 'failure' . mysql_error();
}

Write this way, hope it will work.

Tahmina Khatoon
  • 1,081
  • 3
  • 11
  • 29
1

Just delete this code from your php script and it will be fine.

if(mysql_query($query))
{
    echo 'success';
}
else
{
    echo 'failure' .mysql_error();
}

You make it running error twice in a time. You can also use mysql_affected_rows() to make sure the data is executed in database server. Return a string type value.

<?
$email=$_POST['email'];
$pw=$_POST['pw'];

mysql_connect('***','***','***');
@mysql_select_db('***') or die('Unable to select database');

$query = "INSERT INTO test_table VALUES ('','$email','$pw')";
if(mysql_query($query))
{
    echo 'Data executed : '.mysql_affected_rows();
}
else
{
    echo 'failure' .mysql_error();
}
mysql_close();
?>

Good luck and let me know the result.

Hendry Tanaka
  • 454
  • 3
  • 11
0
$email=$_POST['email'];
$pw=$_POST['pw'];

 $alerts = array();

if (trim($_POST['email']) == '') {
   $alerts[] = "<div class='alert alert-danger' role='alert'> Enter your Email! </div>"; }
if (trim($_POST['pw']) == '') {
   $alerts[] = "<div class='alert alert-danger' role='alert'> Enter your PW! </div>"; }

if (!count($alerts)) {
   $query = "INSERT INTO test_table (email, pw) VALUES ('".$email."', '".$pw."')";
   mysqli_query($this->conn, $query) or die (mysqli_connect_error());
   return ['success' => true];
} else {
   return ['success' => false, 'alert_m' => implode($alerts)."<br>"];
}