user3095385
user3095385

Reputation: 79

Use $_GET together with $_POST

I'm trying to post a new record in a table with <form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">. But every row in my table has an unique id, and that id is put next to every name. So I'm trying to get the id with $_GET but it's been unsuccesful so far. Is the method I'm trying wrong or am I doing something else wrong? If anybody can tell me what's going wrong, I'd appreciatie.

PHP that gets placed above <html>

<?php
    if (isset($_POST['saveRecord'])) {
        if (isset($_POST["newRecord"]) && !empty($_POST["newRecord"])) {
            $id = $_GET['record'];
            $klant=$_POST['newRecord'].$id;
            $query = "INSERT INTO table2
                (recordid, recordname)
                VALUES
                (NULL, '$record')";

            mysqli_query($con, $query);
        }
    }
?>

Markup

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <table>
        <?php
            $query = ("select * from table1");
            $result = mysqli_query($con, $query) or die (mysqli_error());
            while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
            $id = $row['rowid'];
        ?>
        <tr>
            <td>
                <input class="newRecord<?php echo $id; ?>" type="text" name="newRecord<?php echo $id; ?>" />
                <a href="?record=<?php echo $id; ?>">
                    <button class="saveRecord<?php echo $id; ?>" name="saveRecord<?php echo $id; ?>">Save</button>
                </a>
            </td>
        </tr>
        <?php } ?>
    </table>
</form>

Upvotes: 1

Views: 134

Answers (3)

Geoff Atkins
Geoff Atkins

Reputation: 1703

Don't bother trying to do both at once (the $_GET variables will only be passed if it is included in the action of the form).

The script won't pick up the the records from the $_POST as the names of the field have the ID included in them.

Either create each record as an individual form (move the whole lot inside the WHILE loop), or you could use the ID held within the field name, like this:

$newdata = array();
foreach($_POST as $k => $v) {
  if ((substr($k,0,9) == 'newRecord') && (!empty($v)) {
    $id = substr($k,9);
    $klant = $v;

    $newdata[$id] = $klant;
  }
}

Which should extract the ID from the field name and associate it with the data entered to the form.

Upvotes: 2

kodebuilder
kodebuilder

Reputation: 33

move your opening and closing form tags in while loop,it will submit only 1 form at a time,otherwise all the inputs will be submitted.

Upvotes: 0

Saty
Saty

Reputation: 22532

Your button name is

name="saveRecord<?php echo $id; ?>

SO this condition need $id

  if (isset($_POST['saveRecord'])) {// your id missing

Upvotes: 1

Related Questions