Hannah James
Hannah James

Reputation: 570

wpdb->update not working with custom table

I have created custom table in WordPress database and I also created edit form to update the values. Here is my code

<form method="post">
    <table class="table">
        <thead>
            <tr>
                <th></th>
                <th>Item</th>
                <th>Stock</th>
                <th>Update</th>          
            </tr>
        </thead>
        <tbody>
            <?php
                $i=1;
                global $wpdb;
                $results = $wpdb->get_results( 'SELECT * FROM `wp_dvs_stock_details` ORDER BY item ASC', OBJECT );
                foreach ($results as $key => $row) {
                    echo "<tr>";
                    echo "<td>".$i."</td>";
                    echo "<td id='item$i'><input type='text' value='{$row->item}' name='item$i'0 id='item$i' class='form-control' /></td>";

                    echo "<td><input type='number' value='{$row->stock}' name='stock$i' id='stock$i' class='form-control' readonly /></td>";        

                    echo "<td id='change$i'><input class='form-control change' type='number' name='change$i'0 id='change$i' tag=$i /></td>";
                    echo "</tr>";
                    $i++;
                }
            ?>
        </tbody>
    </table>
    <input type="submit" name="edit" id="edit" class="btn btn-success" style="float: right;">
</form>

and here is my code to update the fields

if(isset($_POST['edit'])) {
    $i = 1;
    $table_name = $wpdb->prefix.'dvs_stock_details';
    $results = $wpdb->get_results("SELECT * FROM {$table_name} ORDER BY item ASC");
    foreach ( $results as $row) {
        $item = $_POST['item'.$i.''];
        $sql = $wpdb->update($table_name,
          array(
            'item'=>$item,
            array('id'=>$row->id),
            array('%s'),
            array('%d'))
        );
        print_r($sql);
        $i++;
    }
}

When I click submit I get this error.

with Edit Form my intensions are to update item name and stock. Please help.

Upvotes: 0

Views: 1797

Answers (1)

rajat.gite
rajat.gite

Reputation: 446

You can use like this

$wpdb->update($table_name,
    array(
        'item'      => //item value,
        'stock'     => //stock value,
    ), 
    array(
        'id'    =>  $row->id ,
    )
);

Upvotes: 2

Related Questions