0

I am trying to integrate the php and javascript. I send the javascript variable into php variable. And printed it out in the browser using echo command. It outputs the exact same result that I am expecting. I write following command;

<script>
    var p1 ='Lohuti'
</script>
<?php
            $p1="<script>document.write(p1);</script>";
            $db_connection = pg_connect("host=localhost dbname=postgres user=postgres password=admin");
            $sql = "SELECT * FROM public.flood WHERE jamoat= '".$p1."'";
            echo $sql;
            $result = pg_query($db_connection, $sql);
            while ($row = pg_fetch_row($result)) {
               $row[0]
            }
?>

The echo $sql prints outs SELECT * FROM public.flood WHERE jamoat= 'Lohuti'. But this query unable to fetch the data from a database. If I just replace the php variable $p1 with the name Lohuti, It works fine, I can fetch the data. In my case, I am planning to add the dynamic javascript variable into php variable and query the required result. Is there any solution to this type of problem?

JAY PATEL
  • 559
  • 4
  • 17
Tek Kshetri
  • 2,129
  • 1
  • 17
  • 41
  • Your issue is that `$p1` is not actually `Lohuti`, that's just what you see when you render `` in a browser. See the duplicates for methods to pass a JS variable to a PHP script. – Nick Nov 08 '19 at 07:10
  • 1
    I am following [this answer](https://stackoverflow.com/a/24950211/9354344) this answer. What is the problem with this answer? – Tek Kshetri Nov 08 '19 at 07:14
  • See ToolmakerSteve's comment to that answer. That answer is incorrect. – Nick Nov 08 '19 at 07:17
  • Do you have any good idea to pass the dyanamic javascript variable to php variable? I want less code method. Please suggest me – Tek Kshetri Nov 08 '19 at 07:20
  • 1
    Sorry but there aren't any easy ways, you have to either use a request, by changing location (`http://url/p1=Lohuti`) or submitting a form with e.g. `` or using an ajax request to pass the variable. – Nick Nov 08 '19 at 07:22
  • https://stackoverflow.com/a/8191134 this solution works for me. Thank you for your suggestion. – Tek Kshetri Nov 08 '19 at 08:11
  • I'm glad you found a solution. – Nick Nov 08 '19 at 08:15

0 Answers0