# Adding and updating data to the database using the column names sent by POST

**URL:** <https://www.phphelp.com/t/adding-and-updating-data-to-the-database-using-the-column-names-sent-by-post/35096>\
**Category:** Beginners - Learning PHP\
**Created:** [November 2, 2022, 8:04am UTC](https://www.phphelp.com/t/adding-and-updating-data-to-the-database-using-the-column-names-sent-by-post/35096 "2022-11-02T08:04:10Z")\
**Posts on this page:** 5\
**Page:** 1

<div class="post-metadata">

**Author:** ![Adem](https://www.phphelp.com/letter_avatar_proxy/v4/letter/a/a4c791/32.png) [@Adem](https://www.phphelp.com/u/Adem)\
**Post date:** [November 2, 2022, 8:04am UTC](https://www.phphelp.com/t/adding-and-updating-data-to-the-database-using-the-column-names-sent-by-post/35096/1 "2022-11-02T08:04:10Z")

</div>

Hello,

Since I gathered all the products in one table, a table with 66 columns was created.  
Each product uses specific columns, not all columns.  
Instead of typing the names of 66 columns for adding or updating a new product to the database, how to use the column names and values to be sent by POST for the relevant product update or addition? Is this possible?

POST content for an example product

```auto
$_POST
echo '<pre>' . print_r($_POST, true) . '</pre>';
Array
(
    [kodu] => 6EFFE39
    [adi] => OFSET
    [marka_id] => 12
    [stok] => 1
    [fiyati] => 108.00
    [iskonto] => 0.00
    [ucreti] => 20.00
    [birim_id] => 1
    [tipi_id] => 9
    [boyutu_id] => 92
    [aciklama] => 
)

```

add new data

```auto
    $ap = $db->prepare("INSERT INTO all_products (
			)
        VALUES (
			)");
        $ap->bindParam();
        $ap->execute();

```

edit existing product

```auto
     $edit_id = $_POST['edit_id'];
	 $sql = $db->prepare("UPDATE all_products SET 
     =:,  
     WHERE id=:id ");
 
     $sql->bindParam();
	 $sql->bindParam(':id', $edit_id);
     $sql->execute();

```

---

<div class="post-metadata">

**Author:** ![phdr](https://www.phphelp.com/letter_avatar_proxy/v4/letter/p/91b2a8/32.png) [@phdr](https://www.phphelp.com/u/phdr)\
**Post date:** [November 2, 2022, 8:40am UTC](https://www.phphelp.com/t/adding-and-updating-data-to-the-database-using-the-column-names-sent-by-post/35096/2 "2022-11-02T08:40:40Z")

</div>

You were already told not to do that -

> [@Is it possible to post two separate values when an item is selected with the Select option?](https://www.phphelp.com/t/is-it-possible-to-post-two-separate-values-when-an-item-is-selected-with-the-select-option/35025/23):
>
> Databases are not speadsheets. You should only store data that exists. That table should have one row for each separate piece of product/property data.

And what to do -

> [@Is it possible to post two separate values when an item is selected with the Select option?](https://www.phphelp.com/t/is-it-possible-to-post-two-separate-values-when-an-item-is-selected-with-the-select-option/35025/25):
>
> You would have one product\_type(s) table. It would have columns for -
> 
> 1. an id (which you apparently have)
> 2. product\_id (which you apparently have)
> 3. type (which would be whatever the existing column names are)
> 4. value (which would be whatever the existing stored values are)

By laying out a table like a spreadsheet, every operation to find, order, count, insert, and update data requires more code and more complicated queries.

---

<div class="post-metadata">

**Author:** ![Adem](https://www.phphelp.com/letter_avatar_proxy/v4/letter/a/a4c791/32.png) [@Adem](https://www.phphelp.com/u/Adem)\
**Post date:** [November 2, 2022, 7:45pm UTC](https://www.phphelp.com/t/adding-and-updating-data-to-the-database-using-the-column-names-sent-by-post/35096/3 "2022-11-02T19:45:43Z")

</div>

Thank you for the answer

There is a separate table for each product.  
There is a separate table for each product type and feature.

For a job I was trying to do, I was told that all products should be in one table.  
I have moved all products to one table  
I moved all product types and attributes to one table  
The column counts are plus, but I think it’s better to move them in a single table.  
I have categorized the products. Selected category products are listed.  
Total 40 product categories. The total product is 750 pieces.  
Is this product table big? does it crash the server? I don’t know.

It would be nice if I could “add and update” above.

---

<div class="post-metadata">

**Author:** ![Strider64](https://www.phphelp.com/user_avatar/www.phphelp.com/strider64/32/3161_2.png) [@Strider64](https://www.phphelp.com/u/Strider64)\
**Post date:** [November 2, 2022, 11:51pm UTC](https://www.phphelp.com/t/adding-and-updating-data-to-the-database-using-the-column-names-sent-by-post/35096/4 "2022-11-02T23:51:39Z")

</div>

If you want to use an array use it in a HTML form like the following:

```auto
<form id="formData" class="checkStyle" action="create_procedure.php" method="post">
    <input type="hidden" name="cms[user_id]" value="2">
    <input type="hidden" name="cms[author]" value="<?= Login::full_name() ?>">
    <input type="hidden" name="action" value="upload">
    <input type="hidden" name="cms[page]" value="blog">

    <div class="heading-style">
        <label class="heading_label_style" for="heading">Heading</label>
        <input class="enter_input_style" id="heading" type="text" name="cms[heading]" value="" tabindex="1" required
               autofocus>
    </div>
    <div class="content-style">
        <label class="text_label_style" for="content">Content</label>
        <textarea class="text_input_style" id="content" name="cms[content]" tabindex="2"></textarea>
    </div>
    <div class="submit-button">
        <button class="form-button" type="submit" name="submit" value="enter">submit</button>
    </div>
</form>

```

Here’s how I insert the data using php:

```auto
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = $_POST['cms'];

    try {
        $today = $todayDate = new DateTime('today', new DateTimeZone("America/Detroit"));
    } catch (Exception $e) {
    }
    $data['date_updated'] = $data['date_added'] = $today->format("Y-m-d H:i:s");

    $cms = new CMS($data);
    $result = $cms->create();
    if ($result) {
        header("Location: gallery.php");
        exit();
    }
}

```

Sorry that’s from a different PHP script, but the main thing is `$data = $_POST['cms'];` which is the array that would contain the data and used in the function

Very easy to do.

That way you could do something like this with the PHP code:

```auto
<?php
/*
 * As long as you have the correct field names as the key and
 * the correct values in the corresponding keys the following
 * procedural function should work with no problem.
 *
 */

function insertData(array $data, $pdo, $table) {
    try {
        /* Initialize an array */
        $attribute_pairs = [];

        /*
         * Set up the query using prepared states with the values of the array matching
         * the corresponding keys in the array
         * and the array keys being the prepared named placeholders.
         */
        $sql = 'INSERT INTO ' . $table . ' (' . implode(", ", array_keys($data)) . ')';
        $sql .= ' VALUES ( :' . implode(', :', array_keys($data)) . ')';

        /*
         * Prepare the Database Table:
         */
        $stmt = $pdo->prepare($sql);

        /*
         * Grab the corresponding values in order to
         * insert them into the table when the script
         * is executed.
         */
        foreach ($data as $key => $value)
        {
            if($key === 'id') { continue; } // Don't include the id:
            $attribute_pairs[] = $value; // Assign it to an array:
        }

        return $stmt->execute($attribute_pairs); // Execute and send boolean true:

    } catch (PDOException $e) {

        /*
         * echo "unique index" . $e->errorInfo[1] . "<br>";
         *
         * An error has occurred if the error number is for something that
         * this code is designed to handle, i.e. a duplicate index, handle it
         * by telling the user what was wrong with the data they submitted
         * failure due to a specific error number that can be recovered
         * from by the visitor submitting a different value
         *
         * return false;
         *
         * else the error is for something else, either due to a
         * programming mistake or not validating input data properly,
         * that the visitor cannot do anything about or needs to know about
         *
         * throw $e;
         *
         * re-throw the exception and let the next higher exception
         * handler, php in this case, catch and handle it
         */

        if ($e->errorInfo[1] === 1062) {
            return false;
        }

        throw $e;
    } catch (Exception $e) {
        echo 'Caught exception: ', $e->getMessage(), "\n"; // Not for a production server:
    }

    return true;
}

function updateData(array $data, $pdo, $table): bool
{
    /* Initialize an array */
    $attribute_pairs = [];

    /* Create the prepared statement string */
    foreach ($data as $key => $value)
    {
        if($key === 'id') { continue; } // Don't include the id:
        $attribute_pairs[] = "$key=:$key"; // Assign it to an array:
    }

    /*
     * The sql implodes the prepared statement array in the proper format
     * and updates the correct record by id.
     */
    $sql = 'UPDATE ' . $table . ' SET ';
    $sql .= implode(", ", $attribute_pairs) . ' WHERE id =:id';

    /* Normally in two lines, but you can daisy-chain pdo method calls */
    $pdo->prepare($sql)->execute($data);

    return true;
}

```

I don’t use that PHP code any longer, but I think you should get the idea. Yes, you still have to setup all the columns in the database table and have the corresponding data index (HTML array), but doing it that way is some much easier when inserting and updating the database table.

---

<div class="post-metadata">

**Author:** ![Adem](https://www.phphelp.com/letter_avatar_proxy/v4/letter/a/a4c791/32.png) [@Adem](https://www.phphelp.com/u/Adem)\
**Post date:** [November 3, 2022, 1:48pm UTC](https://www.phphelp.com/t/adding-and-updating-data-to-the-database-using-the-column-names-sent-by-post/35096/5 "2022-11-03T13:48:47Z")

</div>

Thank you so much,  
worked perfectly  
I just made the following change while adding new data, I guess it was overlooked

```auto
$attribute_pairs[] = $value;

```

to

```auto
$attribute_pairs[$key] = $value;

```
