简体   繁体   中英

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

So how should I do the code?

Let's say my form is:

<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" />

The 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...
}
?>

And yes, I'm soo begginer in these stuff and have no idea how this code should work. Thanks for answers.

First, you don't have to set an index to your textareas :

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

Avoid mysql_ driver to connect to database. Please use PDO instead.

PHP side

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

I think that this code could help you.

<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'";
    }

Use PDO instead of mysql php library. => https://stackoverflow.com/a/1402096/1016229

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM