How to do so, if the record exists, it updates, if it does not do an Insert of the same

Asked

Viewed 1,512 times

2

I am a beginner in the forum and in php and I have a question. I have a table with id auto_incremento and name is primary key. There is how I do IF and ELSE using UPDATE and INSERT. Where, if there is name only do update, otherwise do Insert ?

        <?php
        $sql = "SELECT * FROM usuarios";    
                    if(isset($_POST['enviar'])){
                                $result = $conn->query($sql);
                                $row = $result->fetch_assoc();
                    $nome = $_POST['nome'];
                    $cpf = $_POST['cpf'];

                    $result_dados_pessoais = "INSERT INTO usuarios (nome, cpf) VALUES ('$nome', '$cpf')";
                    $resultado_dados_pessoais= mysqli_query($conn, $result_dados_pessoais);
                    //ID do usuario inserido
                    }
        ?>

3 answers

3


By PHP

    <?php

           if(isset($_POST['enviar'])){
                    $nome = $_POST['nome'];
                    $cpf = $_POST['cpf'];
                    $sql1 = ("SELECT * FROM usuarios Where nome='$nome'");
                    $result = $conn->query($sql);
                    $row = $result->fetch_assoc();

                if ($result->num_rows > 0) {
                    $result_dados_pessoais = ("UPDATE usuarios SET cpf='".$cpf."' Where nome='".$nome."'"); 
                }else{
                    $result_dados_pessoais = "INSERT INTO usuarios (nome, cpf) VALUES ('$nome', '$cpf')";
                    //ID do usuario inserido
                }
                $resultado_dados_pessoais= mysqli_query($conn, $result_dados_pessoais);
           }
    ?>

another way with if Else

if(mysqli_query($conn, "SELECT * FROM usuarios WHERE nome = '".$nome."'")) {
    $result_dados_pessoais = mysqli_query($db, "UPDATE usuarios Set cpf = '".$cpf."' WHERE nome = '".$nome."'");
} else {
    $result_dados_pessoais = mysqli_query($conn, "INSERT INTO usuarios (nome, cpf) VALUES ('".$nome."', '".$cpf."')");
}
  • the first way changed all records of the kkkk database

  • @Victor vc had to have completed the update with Where clause, I did not imagine that you did not know that. I edited the answer

  • I had put two clauses Where KKK was for this, but then fixed, actually I can put two clauses right but in a table that contains more fields

  • This is wrong. Another thing, if you check if the name exists and it exists because update the name, it would not only be in Cpf?

  • Yes, I did that is that I created it just to exemplify and get short, but I have fields like : Product Description, Product Code, Unit of Measure that is sold, Reference Code... and then I wanted to know if I could use two Where clauses, I think it should give

  • @Victor ... where name='$name' AND cpf='$Cpf'

Show 1 more comment

3

You don’t need PHP, at least you can ignore it depends on the case.


In Mysql you have a similar feature, which can be done natively with the REPLACE, according to the manual.

REPLACE Works Exactly like INSERT, except that if an old Row in the table has the same value as a new Row for a PRIMARY KEY or a UNIQUE index, the old Row is Deleted before the new Row is inserted. See Section 13.2.5, "INSERT Syntax".

REPLACE works exactly with INSERT, unless an old row in the table has the same value as the new row for PRIMARY KEY or UNIQUE, the old row will be deleted before the new row is inserted.

This may be enough, but of course your database has to be configured correctly and make use of UNIQUE (or PRIMARY KEY).


Another option is to make use of INSERT ... ON DUPLICATE KEY UPDATE, again if your database is using UNIQUE.

When to use the ON DUPLICATE KEY UPDATE, this will make a INSERT, but if there is already a line with these values, a UPDATE in the line containing the figures reported.

  • on Duplicate key does not work since I am doing in php with data coming from a form filled by a user

0

You can do this by SQL even this way:

IF EXISTS (SELECT * FROM usuario WHERE nome = 'NOMEDOUSUARIO') 
BEGIN
   UPDATE ...
END
ELSE
BEGIN
    INSERT INTO ...
END

Try this way in php:

$rs = mysql_query("SELECT * FROM usuarios WHERE nome = '$nome'");
$num = mysql_num_rows($rs);

if($num > 0) {
    //Faça seu update aqui dentro
} else {
    //Faça seu insert aqui dentro
}
  • then but it is a more complex form I created this as a basis, it is for a web system. I wanted to do by PHP

  • I edited the answer with the way I would in php. Take a look there

  • does not rotate this command, nor did Insert in the bank. and I can not function this budega

  • I edited again, one minute you get kkkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.