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

0

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

    
asked by anonymous 02.10.2016 / 17:53

2 answers

0

First select the ID you want to register and make it 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

}
    
02.10.2016 / 18:01
0

You did not detail very well what you want, but I'll try to create an example. Let's assume it's a product, and you get its name and id for 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 you have helped, if that is not the problem, comment there!

    
03.10.2016 / 01:03