Update with IF - SQL MySQL

4

I have to change the value / state to an ENUM ('0', '1') of a field in a table. I'll do it with an UPDATE query with if included.

cambiar_estado.php:

<?php
    //Dormimos el proceso unos segundos...
    sleep(3);

    //Consulta para actualizar el estado en la tabla "usuarios_datos".
    $Sql = "UPDATE usuarios_datos if(estado = '0', SET estado = '1'), if(estado = '1', SET estado = '0') WHERE ID_OBLIGATORIO = '$_REQUEST["Id"];";
?>

<center>
    <?php 
        echo "<a href=\"javascript:cargaXML('cambiar_estado.php?Id=".$_REQUEST["Id"]."','estado".$_REQUEST["Id"]."')\">";
            echo $Sql;
        echo "</a>";
    ?>
</center>
  

Error # 1064 - You have an error in your SQL syntax; check the manual   that corresponds to your MySQL server version for the right syntax to   use near 'if state = 0 SET state = 1 else if state = 1 SET e' at   line 1

    
asked by omaza1990 15.11.2016 в 13:26
source

2 answers

1

Try doing it like this:

$sql = 'UPDATE usuarios_datos 
  SET estado = IF(estado = "0", "1", "0") 
  WHERE ID_OBLIGATORIO = '.$_REQUEST['Id'];

NOTE : I ask you to read about How to avoid SQL injection in PHP?

    
answered by 15.11.2016 в 14:00
0

Hello good day you can add the following logic to the query.

UPDATE usuarios_datos    
set estado =(case estado when 1 then estado=0 when 0 then estado=1 end )

I hope it helps you.

Greetings.

    
answered by 15.11.2016 в 15:11