将javascript变量传递给php mysql选择查询 [英] pass javascript variable to php mysql select query
问题描述
我在php中运行mysql select查询这样
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和var2是同一页面上的javascript变量。我知道客户端变量不能传递给服务器端。但是有变通方法是在同一页面吗?
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.
推荐答案
为了让你做到这一点 - 我相信 - 你必须使用AJAX。
In order for you to make this happen - I believe - you have to use AJAX.
代码如下所示:
$.ajax({
url: 'your_script.php',
type: 'POST',
data: {var1: javascript_var_1, var2: javascript_var_2},
success: function(data) {
console.log("success");
}
});
您的PHP看起来与此类似(不记得JSON编码:
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;
}
?>
然后你可以对结果进行JSON编码成功输出它们。你的PHP脚本 - 但是 - 必须存在于另一个php文件中。
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.
这篇关于将javascript变量传递给php mysql选择查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!