PHP - 在循环内获取和插入

时间:2013-04-30 06:29:27

标签: php loops while-loop

我有问题。我正在使用while循环。我在查询$ rows ['price']里面放了一个。如何将循环内的整个插入值提交到表中?它有5个结果。

page1.php

        <?php

    $sql = mysql_query("SELECT id FROM table where id = '$ID'");

        while($row = mysql_fetch_assoc($sql)){

        echo '<form action = "page2.php" name = "add" method = "post">';
        echo "<b>Price:</b> ";
        echo '<input size = "1" type="text" name="price" value = ""/>';
        echo "%";
        echo "<br/>";

        }

        ?>

    <input type="submit" name="price" value="SUBMIT"/>
    </form>

输出就是这样。

价格:__% 价钱: __ % 价钱: __ % 价钱: __ % 价钱: __ % |提交|

page2.php

             <?php


    if(isset($_POST['submit'])){
        $price = $_POST['price'];

        mysql_query("INSERT INTO items_tbl(price) VALUES('$price');


         ?>

不知何故,它有点工作。我以90,80,70,60,50的形式输入了值。但是表中唯一插入的是最后一个(50)。其余的不。

1 个答案:

答案 0 :(得分:0)

像这样使用,<form>标记应该在while循环之外,你必须将$row['price']放在value

之内
$sql = mysql_query("SELECT price FROM table where id = '$ID'");

echo '<form action = "page2.php" name = "add" method = "post">';
while($row = mysql_fetch_assoc($sql)){
    echo "<b>Price:</b> ";
    echo '<input size = "1" type="text" name="weight'.$row['price'].'" value = ""/>';
    echo "%";
    echo "<br/>";

}

?>
<input type="submit" name="submit" value="SUBMIT"/>
</form>

page2.php 中使用此

$val = implode(",", $_POST);
mysql_query("INSERT INTO items_tbl(price) VALUES('$val');

注意: Please, don't use mysql_* functions in new code。它们不再被维护and are officially deprecated。请参阅red box?转而了解prepared statements,并使用PDOMySQLi - this article将帮助您确定哪个。如果您选择PDO here is a good tutorial