Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
699 views
in Technique[技术] by (71.8m points)

pass javascript variable to php mysql select query

I am running a mysql select query in php like this

<?php
  $getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
  $result=mysql_query($getvalue) or die(mysql_error());

  while($row=mysql_fetch_array($result)){
       extract($row);
       echo $name;
  }
?>

var1 and var2 are javascript variables on the same page. I know client side variable cannot be passed to server side. But is there any workaround as the variables are in the same page.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In order for you to make this happen - I believe - you have to use AJAX.

The code will look like this:

        $.ajax({
            url: 'your_script.php',
            type: 'POST',
            data: {var1: javascript_var_1, var2: javascript_var_2},
            success: function(data) {
                console.log("success");
            }
        });

Your PHP will look similar to this (without keeping in mind the JSON encode:

<?php

$var1 = $_POST['var1'];
$var2 = $_POST['var2'];

  $getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
  $result=mysql_query($getvalue) or die(mysql_error());

  while($row=mysql_fetch_array($result)){
       extract($row);
       echo $name;
  }
?>

Then you can JSON encode the results and pretty much output them on the success. Your php script - however - must live on another php file.

Also, escape your data. Use prepared statements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...