How to know if a record has been made in the database?

Asked

Viewed 124 times

0

How do I check if a certain id has been registered in the database, and if you have not registered using an Insert query and if you are already registered using an update query ?

  • 1

    you can set some field to Unique when Insert fails by violating the Unique restriction, do an update;

2 answers

0

First select the ID you want to register and turn it into a variable.

Then create a query, and then check the results:

SELECT id FROM suaTabela WHERE id=$id

if ($con->num_rows == 1) {

//código afirmando que já existe uma id cadastrada

}
else if ($con->num_rows == 0) {

//codigo afirmando que nenhuma id foi cadastrada

}

0

You didn’t detail very well what you want, but I’ll try to make an example. Let’s assume it’s a product, and you get its name and id by a function:

function trataProduto($conexao, $nomeProduto, $idProduto){
    //Verifica se o produto já existe (pelo id)
    $sql_verifica = "SELECT * FROM lista_de_produtos WHERE produto_id = $idProduto";
    $r = mysqli_query($con, $sql_verifica) ord die(mysqli_error());
    if(mysqli_num_rows($r) >= 1){
        //Faz a query para editar
    }
    else{
        //Faz a query para dar INSERT
    }
}

I hope it helped, if that’s not the problem, comment there!

Browser other questions tagged

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