如何从HTML获取值到PHP变量?

时间:2013-12-04 00:55:03

标签: javascript php html

我需要将用户输入存储到PHP变量中,但我无法这样做。以下是从数据库中获取值的代码:

<?php
    while($Row = mysql_fetch_array($Query_Result)) {
    { 
?>                               
        <tr>
            <td><?php echo $Row['Product_Name'] ?></td>
            <td><?php echo $Row['Product_Type'] ?></td>
            <td><?php echo $Row['Product_Price'] ?></td>

            //the "qty" box does not exist in the database. I want user to enter a number in "qty" box and that number should be stored in a php variable 

            <td><input id="qty" type="number" name="qty" ></td>
            <td><input type="button" value="Add to Cart" onclick="addtocart(<?php echo $Row['Product_ID'] ?>)"</td>
        </tr>

<?php
    }
?>

这是addtocart()函数的Javascript:

<script language="javascript">
    function addtocart(pid) {
        document.form1.Product_ID.value=pid;
        document.form1.command.value='add';
        document.form1.submit();
    }
</script>

<?php
    require 'ConnectDB.php';
    require 'functions.php';

    if(isset($_REQUEST['command']) && $_REQUEST['command']=='add' &&   $_REQUEST['Product_ID']>0 ) {
        $pid=$_REQUEST['Prodcut_ID'];
        // This addtocart() function here sets the qauntity to 1 by default.. I want it to be dynamic. User should input the qauntity and I should be able to pass it to the addtocart()        function

        addtocart($pid,1);
        header("location:shopping.php");
        exit();
    }
?>

请帮忙!

1 个答案:

答案 0 :(得分:0)

上面的代码格式不正确,所以我为你编辑了:

<?php while( $Row = mysql_fetch_array( $Query_Result ) ): ?>
    <tr>
        <td><?php echo $Row['Product_Name'] ?></td>
        <td><?php echo $Row['Product_Type'] ?></td>
        <td><?php echo $Row['Product_Price'] ?></td>

        <!-- the "qty" box does not exist in the database. I want user to enter a  number      in     "qty" box and that number should be stored in a php variable -->

        <td><input id="qty" type="number" name="qty" ></td>
        <td><input type="button" value="Add to Cart" onclick="addtocart(<?php echo $Row['Product_ID'] ?>)"</td>
    </tr>
<?php endwhile ?>

你需要做的就是添加一个输入字段,并将行id放入其中(我假设你的行ID是id ...

<input id="qty" type="number" name="qty[<?php echo $Row['id'] ?>]" >

然后您可以对此使用PHP POST或JavaScript AJAX操作,提交并存储它,这是一个单独的方面,您需要在人们可以帮助之前做出决定...