简体   繁体   中英

php mysql insert query having trouble

I have a query which is not inserting if i use the where clause, without the where clause it inserts data. this is weird and I have never seen it happen before in WAMP

$key=substr(md5(rand(0, 1000000)), 0, 5) ;

$key1="INSERT INTO login(key_id) VALUES('$key') 
WHERE (email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')"

if(mysql_query($key1))  
{
   $message = 'User Added!.';
   echo "<SCRIPT>
   alert('$message');
   location='forgotpassword.php';
   </SCRIPT>";     
}

If I echo $_POST['email_id'] it does return valid result

INSERT and WHERE do not mix. when INSERTing, you are creating a new record. WHERE is used with SELECTing DELETEing or UPDATEing, when you have to specify a filter which rows you want to SELECT, DELETE or UPDATE.

if you want to INSERT a row, do not use WHERE. if you want to change a row, use

$key1="UPDATE login SET key_id = '$key' WHERE
 (email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";

Insert is only used on creating new record and where clause is only used if want to set any condition it is used with like select , update , delete .

Try this it will help:-

  $key1="update login set key_id ='$key' WHERE 
           (email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";

I know @Franz-Gleichmann is already explained very well, whats wrong in your code.

You need to use UPDATE for updating data modified code:

$key1 = "UPDATE login SET key_id = '$key' WHERE
(email_id = '" . mysql_real_escape_string($_POST['email_id']) . "')";

Now i am adding two more points:

  • Please use mysqli_* or PDO , because mysql_* is deprecated and not available in PHP 7.
  • You missed the termination semi colon on the same line, i hope this is typo error.

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