How to use a PHP function inside a JS function [duplicate]

-1

I have a function in PHP (I read that it was recommended to make modifications in the database in PHP and not in JS)

function insertTable()
    {

        $name = 'nome';
        $categoria = 'categoria';
        $download = 1000;
        $upload = 1000;
        $magnet = 'magnet';

        mysqli_query($connect, "INSERT INTO torrents('Nome', 'Categoria', 'DownloadQuantity', 'UploadQuantity', 'Magnet') VALUES ('".$name."', '".$categoria."', ".$download.", ".$upload.", '".$magnet."')");
    }

And in my function in JS (it is in action of a button) I want to call the function insertTable() .

I read that PHP runs on the server and JS runs in the browser, the only way I found it was when the function in PHP is in a separate file, so using AJAX, but I want to do this with both functions in the same file.

    
asked by anonymous 24.01.2017 / 18:57

1 answer

1

Javascript does not have access to your database, so the command can only be done by a script that runs on the server, in the case of PHP, the solution is to make an ajax request, or a POST / GET of one form, as you want to stay on the same page, I think it is more practical AJAX, but in both cases the operation is the same:

  • Your page requests a link
  • This link executes the command in the bank

Do you want everything to be in the same "file"? Make an "if" in the file by validating a parameter passed by your AJAX or POST / GET ($ _FORM [your parameter] that tells your file what to do.

It's not pretty, but it works, but unless you have some sort of access control, it would be at least a security flaw in your application.

    
24.01.2017 / 20:54