John Davidson

php - wpdb->update not working with custom table

0 comments
Message:


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.



My Answer:
The issue in your code is with the way you are using the wpdb->update function. The correct syntax for the wpdb->update function is as follows:

php
$wpdb->update(
$table_name,
array(
'item' => $item,
'stock' => $stock
),
array( 'id' => $row->id ),
array(
'%s',
'%d'
),
array( '%d' )
);


In this code snippet, $table_name is the name of your custom table, 'item' and 'stock' are the columns you want to update, $item and $stock are the values you want to update them to, 'id' is the column to use for the WHERE clause, and '%s' and '%d' are the data types of the values being updated.

You should replace your existing wpdb->update code with the code snippet above to properly update the values in your custom table.

Rate this post

5 of 5 based on 6028 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us