Comparing variables in a query

0

I need to create an if to check if the field coming from POST is empty or not, in case I should be null, if I do not 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())";
    
asked by anonymous 31.07.2015 / 15:32

2 answers

1

Use the function isset() and a if ternary.

$variavel = (isset($_POST["variavel"])?$_POST["variavel"]:"";
    
31.07.2015 / 16:04
1

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

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

I believe this should work:

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

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

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

Once done, just throw the variable in the query.

    
31.07.2015 / 16:32