如何在php mysql查询中获取javascript变量? [英] How to take javascript variable in php mysql query?

查看:68
本文介绍了如何在php mysql查询中获取javascript变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Javascript 和 PHP 的新手.任何人都可以让我知道如何在 php 变量中获取 javascript 变量,我想在 MySQL 查询中使用该 php 变量从 MySQL 数据库中获取数据.是否可以在 MySQL 查询中直接获取 javascript 变量?

I am new to Javascript and PHP. Can anyone let me know how to take javascript variable in php variable and I want to use that php variable in MySQL query to fetch the data from MySQL database. Whether it is possible to take javascript variable directly in MySQL query?

我已经尝试过,但我无法得到结果.我在下面附上了代码

I have tried but I am unable to get the result. I have attached code below

<script>
var baccount = document.getElementById('accountid');
var bacc = baccount.value;
</script>

<?php 

$abcd = '"+bacc+"';

$quer=mysql_query("SELECT * from fpay_user where account_id='$abcd'");


$result=mysql_fetch_array($quer);

$rbal = $result['balance'];

echo $rbal;

?>

推荐答案

事情并没有那么简单.Javascript 在浏览器(客户端)中运行,而 php 在 Web 服务器(主机)上运行.这是两台不同的电脑.要将数据从客户端传递到主机,您可以从 javascript 向服务器上的特定 url 发出 http 请求.当服务器发送其响应时,您可以再次在 javascript 中处理它.

It is not as simple as that. Javascript runs in the browser (the client) and php runs on the web server (the host). These are two different computers. To pass data from the client to the host, you can make an an http request from javascript to a specific url on the server. When the server sends its response you can process it in javascript again.

一个例子(使用 jQuery)是:

An example (using jQuery) would be:

<script>
  // success will be called when the server sent a response.
  function success(result) {
    // result.responseJSON is a javascript object: { balance: 1234 }
    let balance = result.responseJSON.balance
  }

  $.ajax({
    url: '/path/to/script.php',
    data: {
        bacc: baccount.value
      },
    success: success,
    dataType: 'json'
  });
</script>

在 php 中,您可以获取传递的值,执行查询并返回结果:

In php you can fetch the passed value, do your query and return the result:

<?php
  // get the passed value
  $abcd = $_GET['bacc'];

  // do the query SAFELY. See explanation below.
  $quer = mysql_query("SELECT * from fpay_user where account_id='" . mysql_escape_string($abcd) . "'");
  $result=mysql_fetch_array($quer);

  // Now return the result as json string
  header('Content-Type: application/json');
  // This will encode the result as: "{balance: 1234}"
  echo json_encode($result);

一件非常重要的事情.您应该始终使用诸如 mysql_escape_string 之类的东西来清理接收到的值.如果您不这样做,您的软件很容易受到 SQL 注入的影响.我已将此函数调用添加到您的示例中.

One very important thing. You should always sanitize the received values with something like mysql_escape_string. If you do not do that, your software is susceptible to SQL injection. I have added this function call to your example.

这篇关于如何在php mysql查询中获取javascript变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆