簡體   English   中英

PHP如何循環從html表單獲取的數據並將其保存到mysql數據庫中?

[英]PHP how do I loop data which I got from html form and save them into mysql databse?

那么我應該如何編寫代碼?

假設我的表格是:

<form action="check.php" method="POST">
<textarea name="ans[0]"> </textarea>
<textarea name="ans[1]"> </textarea>
<textarea name="ans[2]"> </textarea>
<textarea name="ans[3]"> </textarea>
<input type="submit" />

check.php:

<?php
include('mysql.php'); // in this file i get connected to my db
foreach($ans as $index)
{
    //I want to make this to do that: 
    mysql_query("UPDATE mytable SET $ans = '$ans[1]' WHERE user = 'Me'"); // How do I make that to update $ans[0] for first loop scan, than in next loop scan $ans[1] then $ans[2] and so on...
}
?>

是的,在這些方面我太入門了,不知道這段代碼應該如何工作。 感謝您的回答。

首先,您不必為文本區域設置索引:

<textarea name="ans[]"> </textarea>

避免mysql_驅動程序連接數據庫。 請改用PDO。

PHP方面

if(isset($_POST['ans']) AND is_array($_POST['ans'])){
    $ans = $_POST['ans'];
    foreach($ans as $content){
        //your query
        $db->query("UPDATE table ......");
    }
}

我認為這段代碼可以為您提供幫助。

<form action="check.php" method="POST">
    <textarea name="ans[0]"> </textarea>
    <textarea name="ans[1]"> </textarea>
    <textarea name="ans[2]"> </textarea>
    <textarea name="ans[3]"> </textarea>
    <input type="submit" />
</form>
<?php
    $ans = (array) (isset($_POST['ans']) ? $_POST['ans'] : null);

    foreach($ans as $index=>$value)
    {
        $query = "UPDATE mytable SET `$index` = '$value' WHERE user = 'Me'";
    }

使用PDO代替mysql php庫。 => https://stackoverflow.com/a/1402096/1016229

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM