-4
I need to pass a variable from PHP in a clause WHERE of a SELECT, but this PHP variable gets a value from JAVASCRIPT.
I ran a test passing only a native PHP value and it worked:
<?php
$phpNum = 1; /* Testando com numérico */
$phpTxt = 'teste'; /* Testando com texto */
$sqlNum = mysqli_query($conn,"SELECT * FROM tab1 where campo ='".$phpNum."'");
$sqlTxt = mysqli_query($conn,"SELECT * FROM tab2 where campo ='".$phpTxt."'");
?>
Both selects worked perfectly!
Now if these PHP variables receive Javascript value, then the query fails. I’m getting the JS values as follows:
<script type="text/javascript">
var jsNum = 1;
var jsTxt = 'teste';
</script>
<?php
$phpNum = '<script>document.write(jsNum)</script>';
$phpTxt = '<script>document.write(jsTxt)</script>';
/* Se testar a saída com um echo a saída acontece perfeitamente também */
$sqlNum = mysqli_query($conn,"SELECT * FROM tab1 where campo ='".$phpNum."'");
$sqlTxt = mysqli_query($conn,"SELECT * FROM tab2 where campo ='".$phpTxt."'");
/* Nesse momento que ocorre a falha da query, mesmo testando selects individualmente */
?>
How I can pass the correct JS value to PHP (numeric or text) so that this PHP variable can be correctly assigned in SELECT ???
you will have to make a "api" in php to receive ajax requests or whatever coming from javascript by POST/GET/PUT/DELETE and etc. Try a search on "restful".
– Lucas Trevisan
If that’s what I’m thinking, it’s all literally wrong. Nothing makes sense. What is in Javascript is never read by PHP, so you can communicate Javascript with PHP you need to make a request, using AJAX, as mentioned above. This way you can send to a "page" the data that was generated or defined by Javascript.
– Inkeliz
Php can read JS yes. And for what I’m doing it has to be that way. Maybe just some conversion feature like JSON is missing.
– Eduardo Pereira
There is no way PHP can read the javascript guy. Where did you see this? Javascript is a language that works ONLY there on the front end and php works there on the server, in the back end. It’s IMPOSSIBLE for him to read the javascript stuff the way you want. What you have to do is make REQUESTS for php sending the javascript data. Now php reading the javascript is clueless.
– Lucas Trevisan
Because it’s a brother, but if you do so: $varPHP = '<script>Document.write(varJS)</script>'; You will see that it is possible yes...
– Eduardo Pereira
I’ll ask otherwise then rsrsr. If I have a Javascript var X and want to pass it in the Where clause of this select, as I would then ?
– Eduardo Pereira
Eduardo, understand this: php is interpreted by the server and javascript by the browser. Respect the order of things. First your code is interpreted by the server and after that returns to the browser, probably an HTML, and then your javascript code is interpreted by the browser. As they said above, search for the Rest and ajax api.
– Marcos Kubis