How to check if it already exists in bd?

2

Well, I have following code:

<?php
$link = mysqli_connect("localhost", "root", "vertrigo", "recebecores");


$red = $_GET["red"];
$green = $_GET["green"];
$black = $_GET["black"];


$procura1 = mysqli_query($link, "SELECT * from recebescores where red='$red' AND green='$green' AND black='$black'");
$array1 = mysqli_fetch_array($procura1);


if($array1["red"] == ""){

$inserir1 = mysqli_query($link, "INSERT INTO recebecores (red, green, black) VALUES ('$red', '$green', '$black')"); 

}

?>

I want to check if a record with this same data already exists in the database, but it is not working and it continues to enter the same data.

How could I do this with php?

    
asked by anonymous 24.07.2017 / 00:02

1 answer

6

The problem is that you wrote different table names, I do not think one of them even exists:

//Primeiro comando
"SELECT * from recebescores where red='$red' AND green='$green' AND black='$black"

//Segundo comando
"INSERT INTO recebecores (red, green, black) VALUES ('$red', '$green', '$black')"

Got it? The first time you used the recebescores table and the second time you used the recebecores table.

Even though it works, I recommend using mysqli_affected_rows or mysqli_num_rows :

<?php
$link = mysqli_connect("localhost", "root", "vertrigo", "recebecores");

$red = $_GET["red"];
$green = $_GET["green"];
$black = $_GET["black"];

$procura1 = mysqli_query($link, "SELECT * from recebecores where red='$red' AND green='$green' AND black='$black'");

if(mysqli_num_rows($procura1) > 0){
    $inserir1 = mysqli_query($link, "INSERT INTO recebecores (red, green, black) VALUES ('$red', '$green', '$black')"); 
}
?>

Take a look at the mysqli_affected_rows documentation and the mysqli_num_rows .

    
24.07.2017 / 00:07