Comparing variables in a query

Asked

Viewed 49 times

0

Good need to create an if to check whether the field coming from the POST is empty or not, if it is should set null, if not I Seto the value that came in the variable.

$query2 = "INSERT INTO tbl_CLIENTES_PF (COD_IDENT_CLIEN, TXT_NATUR_CLIEN, 

TXT_NACIO_CLIEN, DAT_NASCI_CLIEN, TXT_OCUPA_ATUAL, TXT_NOMEX_CLUBE, TXT_ALTUR_CLIEN, TXT_PESOX_CLIEN, TXT_ENDER_TWITR, TXT_ENDER_FACEB, TXT_ENDER_YOUTB, TXT_DATAX_ADMIS, TXT_GOSTO_CLIEN, TXT_NGOST_CLIEN, COD_IDULT_ATUAL, DAT_ULTIM_ATUAL) VALUES";
$query2 .= "('$COD_IDENT_ULTIM_CLIEN','$naturalidade','$nacionalidade', "(strcmp($dtnasc, "") == 0 ? 'null' : "'" . $dtnasc . "'")" '$dtnasc','$ocupacao','$clube','$altura','$peso','$twitter','$facebook','$youtube','$desde','$gostede','$naogostade', '$usurLoga', now())";
  • if (isset($_POST['name']) { do something; } Else { do something else; }

  • does not work, for what I want, I want to test the variable, look at my query la

  • if (isset($_POST['name']) { $query2 = "bla bla bla"; } Else { $query2 = null; }

  • That’s not what I want, look at my example, the error is in the quotation marks, I don’t know how to put them

  • Dude, don’t you want to check if a POST is empty or not? Why do you want to do this in the middle of the query if you can simplify it the way I told you? In case I would recommend you to use PDO because this business of storing query inside variable is no longer recommended.

  • Actually it’s not quite the post, it’s variable.

  • then use if (!is_null($variable)) {# code...}

Show 2 more comments

2 answers

1


Use the function isset() and a if ternary.

$variavel = (isset($_POST["variavel"])?$_POST["variavel"]:"";

1

I think the problem is that you are passing the variable even after you have already set the parameter (null or dtnasc):

"(strcmp($dtnasc, "") == 0 ? 'null' : "'" . $dtnasc . "'")" '$dtnasc',

I believe that this way should work:

".(strcmp($dtnasc, "") == 0 ? 'null' : $dtnasc)."

But I think as others have explained, it’s better and more understandable for future maintenance, in this way:

if(isset($_POST['dtnasc'])){$dtnasc = $_POST['dtnasc'];}else{$dtnasc = NULL;}

Once done, just play the variable in the query.

  • Giving error @axe Jhonathan

  • ".(strcmp($dtnasc, '') == 0 ? 'null' : '\''.$dtnasc.'\'')." The strcmp function has to be done with single quotes, explaining in a simple way is because otherwise it ends up "leaving" the function, because the string is being made through double quotes, and when it is not null there has to be the '\'' because it is query parameter as well as '$nacionalidade', '$naturalidade' etc... I think this will solve your problem...

Browser other questions tagged

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