[英]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.