繁体   English   中英

从php脚本中的html表单获取变量

[英]get variable from html form in php script

我是php / html的新手,我正尝试从html表单获取值并将其设置为外部php脚本中的变量。

此变量用于在postgres数据库中运行SQL。 通过单击按钮触发php脚本。

我的猜测是使用get值是html形式的文本:

$SQL = $_GET['get_value'];

但是我无法正常工作。 有人可以帮我解释一下怎么办吗?

我的html代码如下:

<!DOCTYPE html>
<html>
<body>

<form name="SQL" action="query_map.php" method="get">
  SQL:<br>
  <input type="text" name="SQL" id="get_value">
  <br>
 </form>
<button type="submit" id="script-button">
    Run the script
</button>

<script>
function runScript() {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState === 4) {
            if (request.status === 200) {
                alert('Ran the script, result was ' + request.responseText);
            } else {
                alert('Something went wrong, status was ' + request.status);
            }
        }
    };
    request.open('POST', 'http://localhost:8076/query_map.php', true);
    request.send(null);
    return false;
};

document.getElementById('script-button').onclick = runScript;
</script>

</body>
</html>

php代码如下:

<?php 
  $SQL = $_GET['get_value'];
  $db = pg_connect("host=localhost dbname=kopse_hof_put_25 user=postgres password=baf45baf")
    or die ("Could not connect to server\n"); 

    $query = pg_query($db, "create or replace view resultaat as
            select *
            from put_25_vlak_1_vulling
            where id = $SQL");
?>

我在Chrome控制台中看不到任何错误。 我测试了PHP,并且工作正常。

您通过输入名称(而不是id)阅读GET和POST,因此应为:

$SQL = $_GET['SQL'];

使用通用的POST / GET

$SQL = $_REQUEST["SQL"];

我相信我找到了解决方案,这要归功于@ Rahul Dambare

我在表单中添加了一个。 所以我的表格如下:

<form name="SQL" action="query_map.php" method="get">
  SQL:<br>
  <input type="text" name="SQL" id="SQL">
  <br>
  <input type="submit">
 </form>

然后出现以下错误:

错误:输入第4行末尾的语法错误:第9行的C:\\ xampp \\ htdocs \\ query_map.php中id = ^。

存在此错误的原因是因为我的SQL认为我的响应是文本。 有两种可能的解决方案。 第一种解决方案是将文本类型的形式更改为整数。

第二种解决方案是添加pg_escape_string在SQL中加引号。 的PHP如下:

 <?php $test = $_REQUEST['SQL']; $SQL = pg_escape_string($test); $db = pg_connect("host=localhost dbname=kopse_hof_put_25 user=postgres password=password") or die ("Could not connect to server\\n"); $query = pg_query($db, "create or replace view resultaat as select * from put_25_vlak_1_vulling where id = $SQL"); 

谢谢你的帮助

暂无
暂无

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

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