简体   繁体   中英

insert a record or if exist then update in mysql doesnt work

i want that if a record doesnt exist i add it otherwise update it... but it doesnt work, whats the wrong with this code:

<?php
      $user_id=$_POST['user_id'];
      $user_email="user_email";
      $last_stage=$_POST['last_stage'];
      $score=$_POST['score'];
      $note=$_POST['note'];

      $con=mysqli_connect("localhost","ferfer","Drfrj","ferfw");
      $result = mysqli_query($con,"SELECT user_email FROM rating WHERE user_email='".$user_email."'");
      $num_rows = mysqli_num_rows($result);

      if ($num_rows > 0) {
        //echo "exist";
        mysqli_query($con,"UPDATE rating SET user_id=".$user_id.", user_email='".$user_email."', last_stage=".$last_stage.", score=".$score.", note='".$note."'  WHERE user_email='".$user_email."'";
        mysqli_close($con);
      }else{
        //echo "does not exist";
        mysqli_query($con,"INSERT INTO rating(user_id, user_email, last_stage, score, note)VALUES (".$user_id.",'".$user_email."',".$last_stage.",".$score.",'".$note."') ");          
        mysqli_close($con);
      }
 ?>

You can actually do it in a single query since MySQL has implemented INSERT ... ON DUPLICATE KEY UPDATE which basically INSERT sa record if it does not exists otherwise UPDATE s it.

The first thing you need to do is to add a UNIQUE column on the table. In your example I see that user_email is the column you are searching for existence. If this is not unique, you need to alter the table for UNIQUE constraint

ALTER TABLE rating ADD CONSTRAINT tb_uq UNIQUE(user_email)

after it has been implement, build a query like this,

INSERT INTO rating(user_id, user_email, last_stage, score, note)
VALUES($user_id, '$user_email', last_stage, score, '$note')
ON DUPLICATE KEY UPDATE
   user_id = $user_id, 
   last_stage = $last_stage, 
   score = $score, 
   note= '$note'

As a sidenote, the query is vulnerable with SQL Injection if the value( s ) of the variables came from the outside. Please take a look at the article below to learn how to prevent from it. By using PreparedStatements you can get rid of using single quotes around values.

$user_email="user_email";

should be changed to

$user_email=$_POST['user_email'];

And missing ( simbol, as @Yogesh Suthar said. You should also consider escaping characters in strings, using ie mysql_real_escape_string function.

you forgot ) here

mysqli_query($con,"UPDATE rating SET user_id=".$user_id.", user_email='".$user_email."', last_stage=".$last_stage.", score=".$score.", note='".$note."'  
WHERE user_email='".$user_email."'");
                                   ^ // here

Better way is to use

REPLACE INTO `rating` (user_id,user_email,last_stage,score,note)
VALUES(@user_id,@user_email,@last_stage,@score,@note) WHERE user_email=@email

use also binding and prepared statements to make it more secure. Your code is very insecure because you have nor escape functions neither casting.

Example of using binding with PHP. $dbh is PDO object.

$stmt = $dbh->prepare("REPLACE INTO `rating` (user_id,user_email,last_stage,score,note)
VALUES(@user_id,@user_email,@last_stage,@score,@note) WHERE user_email=@email");
$stmt->bindParam('@name', (int)$user_id);
$stmt->bindParam('@user_email', $user_email);
$stmt->bindParam('@last_stage', $last_stage);
$stmt->bindParam('@score', $score);
$stmt->bindParam('@note', $note);

more on http://pl1.php.net/pdo

with binding you don't have to escape strings because it goes straight into the database layer without it having to be crudely spliced into the SQL statement.

The MySQL REPLACE statement works like the INSERT statement with the additional rules:

If the record which you want to insert does not exist, the MySQL REPLACE inserts a new record. If the record which you want to insert already exists, MySQL REPLACE deletes the old record first and then insert a new record.

$user_email="user_email"; should be $user_email=$_POST["user_email"];

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