How to check if it already exists in the comic book?

Asked

Viewed 62 times

2

Well, I have this 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 it already exists in the database, some record with the same data, but it is not working and it continues to insert me equal data.

How could I do this with php?

1 answer

6


The problem is that you wrote different table names, I believe one of them doesn’t even exist:

//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 table recebescores and the second time used the table recebecores.

Even if it works, I recommend using the 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 documentation of mysqli_affected_rows and of mysqli_num_rows.

  • 1

    Have you checked the table names? Have you solved them yet?

  • Got it! Thanks, the problem was even in the table name I had not read...

Browser other questions tagged

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