Can I use a SELECT inside the IF?

Asked

Viewed 659 times

-2

It occurred to me to try to do this action, but it seems to give error. It is possible?

//EVITANDO DUPLICIDADE
if ($legenda > "0") {
    SELECT legenda FROM aula_upload_arquivo WHERE legenda = $legenda;
    echo 'Existe esse arquivo';
} else {
    echo 'Não existe o arquivo';
}

3 answers

2

You can, but not this way. In order to use SQL you must use some function for this, such as mysqli_query or equivalent.

That way, it would be like doing:

if ($legenda > 0) {
   $result = mysqli_query($con, "SELECT legenda FROM aula_upload_arquivo WHERE legenda = '$legenda'");
   // ...
} else {
   // ...
}

There is nothing wrong with running a query inside a if. If that’s already what you’re doing, then mention the exact error that occurs.

0

PROBLEM SOLVED:

01) It was not necessary to do this action with SELECT within IF. 02) Much easier, it was to transform one of the fields into UNIQUE 03) So that the data is always exclusive, the information was inserted in the field, using the user’s name and his ID, along with any noun.

0

$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$result = mysqli_query($conn, "SELECT * FROM table WHERE dado='$dado'");
if(mysqli_num_rows($result) > 0){
echo "Este Dado já existe";
exit();
} else {
 if(mysqli_query($conn, "INSERT INTO table (dado) VALUES ('$dado')");
 echo "Dados inseridos com sucesso";
}
  • Hi, Leandro. Sorry, I forgot to mention. I use the PDO system. I couldn’t fit your answer to test. And I don’t know how to turn from msqli to Pdo. :-(

  • Bacco, Why do not you take Advantage of it and Answer the Question? An IF loop was made with an MSQLI Response and Accurate in PDO. Another Question, about CLASSES, IF, INSERT and also no Answer. Why not help, Instead of Hinder?

  • @Bacco, read this not Please

  • @Tátto the response of Inkeliz does not work as desired? It is the same with PDO.

  • @Noobsaibot, thank you for helping me. It didn’t work out. Because like all my system is in PDO, when I put the application with msqli ended up giving conflict, because it has the UPLOAD system CLASS that locks many actions that are made within the code.

  • Noobsaibot, I followed what @Bacco said and changed the system to the field: "identifies" as UNIQUE. Got show, really no more to duplicate, but, generated me another problem, because, as has the CLASS in Upload, appear some errors. I’ll put them in the next comment.

  • In the first insertion of the field "identifies", beauty, register normally, but in the second comes this error, by the way, these errors:

  • I can’t post my mistakes here...

  • How to insert errors here?

  • You can edit the question.

Show 5 more comments

Browser other questions tagged

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