从HTML表单向php变量传递值

d4so4syb  于 2023-05-21  发布在  PHP
关注(0)|答案(3)|浏览(150)

我试图从HTML表单传递一个值,并将其存储到一个php变量中,这样我就可以在查询中使用这个变量来确定从数据库中获取哪一行。我使用_post['category']来获取所选的值,并将变量传递给查询以获取所需的行,但到目前为止我没有得到任何帮助。以下是我到目前为止写的:

<form method="post" action="a34.php">                                                                    
 <select name="category">
  <option value="6008">15</option>
  <option value="6018">25</option>
  <option value="6034">30</option>
  <option value="6038">40</option>



$V=$_POST['category'];

$getrow= "SELECT ProdID, 
ProdCatID, ID_AC_seperate, ProdImage,
 ProdName, ProdPrice, ProdShippingPrice, 
ProdShortDesc, ProdMediumDesc, suitable, 
cart_thumb FROM accessories WHERE ProdID = '$V'";
n53p2ov0

n53p2ov01#

我建议你使用strip_tags函数。永远不要把原始数据放进sql。
所以呢

If(isset($_POST['category']) {
    $data = strip_tags ($_POST['category']);

    $getrow= "SELECT ProdID, ProdCatID, ID_AC_seperate, ProdImage,
                     ProdName, ProdPrice, ProdShippingPrice, 
                     ProdShortDesc, ProdMediumDesc, suitable, cart_thumb
              FROM accessories 
              WHERE ProdID = '. $data .'";
}
yrdbyhpb

yrdbyhpb2#

好吧,试试下面的。
JS文件检测用户何时单击一个选项,并向updateRow.php文件发送一个 AJAX 请求,其中$_POST变量为val
updateRow.php接受$_POST变量并将其转换为整数。然后用该变量更新查询。处理查询,然后执行echoprint等。以所需的HTML格式显示数据。否则,数据回显“失败”。
然后将回显、打印等输出发送回变量data下的JS文件。如果数据等于“失败”,则输出错误消息。否则,它将HTML插入#row元素中。

// ------ Your JS file ---------

$(function() {
  $row = $("#row");

  $("#update-row").on("change", function() {
    var val = $("select option:selected", this).val();
    $.post('updateRow.php', {
      val: val
    }, function(data) {
      if (data == 'failure') {
        $row.text("Sorry, the row does not exist");
      } else {
        $row.html(data);
      }
    });
  });
});
//------- updateRow.php ---------
//Make sure path/to/updateRow.php in the JS file is updated to here

$V = (int) $_POST['val'];

$getrow = "SELECT ProdID, 
ProdCatID, ID_AC_seperate, ProdImage,
ProdName, ProdPrice, ProdShippingPrice,
ProdShortDesc, ProdMediumDesc, suitable,
cart_thumb FROM accessories WHERE ProdID =" . $V;

if ( QUERY_IS_SUCCESSFUL() ) {
  echo 'The <b>HTML</b> you want to display the data in';
} else {
  echo 'failure';
}
<!----- HTML file ---->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="path/to/js/file.js"></script>

<form method="post" action="a34.php" id="update-row">
  <select name="category">
    <option value="6008">15</option>
    <option value="6018">25</option>
    <option value="6034">30</option>
    <option value="6038">40</option>
    </select>
</form>

<div id="row"></div>
628mspwn

628mspwn3#

例如,请参见,然后相应地更改代码

Name: <input type="text" name="name"><br><br>
<input type="submit" name="submit" value="Submit">
</form>

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['name'];
if (empty($name)) {
  echo "Name is empty";
} else {
  echo $name;
}
}
?>```

相关问题