简体   繁体   中英

success/error message for insert into mysql database

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();
?>

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.

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.

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.

$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>"];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM