简体   繁体   English

将javascript变量传递给php mysql select查询

[英]pass javascript variable to php mysql select query

I am running a mysql select query in php like this 我正在像这样在php中运行mysql选择查询

<?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. var1和var2是同一页面上的javascript变量。 I know client side variable cannot be passed to server side. 我知道客户端变量无法传递到服务器端。 But is there any workaround as the variables are in the same page. 但是有什么变通办法,因为变量在同一页面中。

In order for you to make this happen - I believe - you have to use AJAX. 为了使这种情况发生-我相信-您必须使用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看起来与此类似(无需记住JSON编码:

<?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. 然后,您可以对结果进行JSON编码,并在成功时将其输出很多。 Your php script - however - must live on another php file. 您的php脚本-但是-必须存在于另一个php文件中。

Also, escape your data. 另外,转义数据。 Use prepared statements. 使用准备好的语句。

In theory, you could pass the vars to php via some sort of ajax call. 从理论上讲,您可以通过某种Ajax调用将vars传递给php。 I think it would go something like... 我认为它会像...

JavaScript: JavaScript:

var data = {
    'var1': $('selector').val(),
    'var2': $('selector').val()
};

$.ajax({
    type: 'post',
    url: 'path-to-your-file.php',
    data: data,
    timeout: 50000
}).done(function(response) {
    console.log(response);
}).fail(function(error) {
    // uh-oh.
});

php: 的PHP:

<?php
print_r($_POST['data']);

Otherwise, you could use: 否则,您可以使用:

  • cookie 曲奇饼
  • hidden input 隐藏的输入

php: 的PHP:

<?php 
... column1='$_COOKIE["mycookie1"]' and column2='$_COOKIE["mycookie1"]'";
... column1='$_POST["hidden1"]' and column2='$_POST["hidden2"]'";

NOTE: you will want to sanitize the data. 注意:您将要清理数据。 Using raw cookie and/or input values could lead to some less than desirable results. 使用原始Cookie和/或输入值可能会导致一些不太理想的结果。

Use Method Post in AJAX or Form!! 使用AJAX或表格形式的方法发布!! To send js variable in Php and receive it in php using $_post[ name_of_obj ]; 使用$ _post [name_of_obj]在PHP中发送js变量并在php中接收它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM