Edit duplicate if mysqli php exists

I have some problems with my mysqli INSERT code. I really don't know how to handle duplicates, but I read a lot of posts there, and I tried to get it to work, but when I execute this code with the same variables, the number of lines increases. Could you help me fix this code or find another way to check for duplicates?

  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);
  // Check connection
  if ($conn->connect_error) {
     die("Connection failed: " . $conn->connect_error);
  }


  if ($stmt = $conn->prepare(
    "INSERT INTO matka (jmeno, prijmeni, bydliste, telefon, email)
    VALUES (?,?,?,?,?)
    ON DUPLICATE KEY UPDATE
    jmeno = VALUES(jmeno),
    prijmeni = VALUES(prijmeni),
    bydliste = VALUES(bydliste),
    telefon = VALUES(telefon),
    email = VALUES(email)" )) {
  $stmt->bind_param("sssss", $jmeno_matky, $prijmeni_matky, $bydliste_matky, $telefon_matky, $email_matky);
  $stmt->execute();
  printf("%d Row inserted.\n", $stmt->affected_rows);
  $stmt->close();
  $id_matky = $conn->insert_id;
  $conn->close();
  }
+4
source share
1 answer

ON DUPLICATE KEYrelies on the presence of a PRIMARY or UNIQUE key. This means that the column (s) that the key is specified cannot be the same for two rows.

If you, for example, made a UNIQUE key on emailas follows:

CREATE INDEX matka_email ON matka (email)

, , ON DUPLICATE KEY

: :

CREATE INDEX matka_alldata ON matka (jmeno, prijmeni, bydliste, telefon, email)

. :

+6

Source: https://habr.com/ru/post/1670675/


All Articles