WHERE clause with PHP coming from JavaScript [closed]

-4

I need to pass a PHP variable into a WHERE clause of a SELECT , but this PHP variable receives a value from JAVASCRIPT .

I ran a test passing just 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 are given 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 can I pass the correct value from JS to PHP (numeric or text) so that this PHP variable can be correctly assigned in SELECT ???

    
asked by anonymous 29.08.2016 / 02:13

1 answer

2

The way you put it you will not be able to make it work because JavaScript runs on the client side and not on the server side. One way to resolve this is to get these values with $_GET as in the example below

<?php
$phpNum = $_GET['phpNum'];    /* Testando com numérico */ 
$phpTxt = $_GET['phpTxt'];   /* Testando com texto    */
$sqlNum = mysqli_query($conn,"SELECT * FROM tab1 where campo ='".$phpNum."'");
$sqlTxt = mysqli_query($conn,"SELECT * FROM tab2 where campo ='".$phpTxt."'");
?>

Then you can execute the above code by passing the phpNum and phpTxt values via url like this: seuscript.php?phpNum=1&phpTxt=teste

That way yes you can get through JavaScript. You can use the $.ajax utility of the jQuery library (read more at link )

You can also search for ajax acquisition with JavaScript.

    
29.08.2016 / 13:44