How do I insert a row in the sql table when I click the button?

1

I have a real estate website that I'm implementing the favorites option. When you open the property and click favorite, it should insert a new row in the favorite table, the one below (status 1 is favorite), and if you "uncheck" it removes the row:

id|idusuario|imovel|status
1 |   789   | 552  |  1

My question is how to do this dynamically, realtime. I have the $ idusuario and $ idimovel variables.

PHP code to insert or remove from favorites, just do not know how to dynamically call, without opening another page:

$query = ("INSERT INTO favoritos (idusuario, imovel, status)
VALUES ('".$idusuario."', '".$idimovel."', '1'");
$db->setQuery($query);
$db->execute();
    
asked by anonymous 16.05.2018 / 20:14

1 answer

3

O $.ajax() :

$('#ID_DO_BOTAO').on('click',function(){
    $.ajax({
        type:"POST",
        url:"SEU_ARQUIVO.php",
        dataType:"Json",
        data:{'favorito':'favorito'},
        success:function(a){
            //retorno do php, ou um reload da pagina/elemento
        }
    });
});

YOUR_ARQUIVO.php

if(($_POST['favorito'])&&($_POST['favorito']=='favorito')){
    //primeiro vc executa uma verificação se o usuário ja clicou ("SELECT * FROM favoritos WHERE idusuario = '$idusuario');
    if(usuario ja clicou){
        $query=("DELETE FROM favoritos WHERE idusuario = ".$idusuario." AND imovel = ".$idimovel);
    }else{
        $query = ("INSERT INTO favoritos (idusuario, imovel, status)
        VALUES ('".$idusuario."', '".$idimovel."', '1'");
        $db->setQuery($query);
        $db->execute();
    }
}
    
16.05.2018 / 21:03