Home » Php » Update/insert only a column of database table in PHP

Update/insert only a column of database table in PHP

Posted by: admin February 25, 2020 Leave a comment

Questions:

I WordPress table named wp_fes_vendors, there is a total of 12 columns.

Out of these 12 columns, I want to only update the data of column name requests

The data i am getting for this column is from a custom form in backend stored in $_POST['getval']

Here is code i tried

 if (!empty(isset($_POST['getval'])))
    {       
            global $wpdb;
            $table_name=$wpdb->prefix.'fes_vendors';

            $data_array = array(

            'requests' => $_POST['getval']


            );

            $data_where = array('requests' => $_POST['getval']);

            $wpdb->update($table_name,$data_array,$data_where);


    }

Html

<form id="myForm" name="myform" action="" method="POST" style="padding:20px;">
  <label> Select if this Vendor wishes to receive customer requests or not: </label>
  <select name="getval" id="brandSel" size="1">
      <option selected="selected" disbaled value="">-- Select status --</option>
      <option value="1">Enable</option>
      <option value="0">Disable</option>
  </select>

  <?php submit_button('submit'); ?>
</form>

I tried several times but the data is not being saved /updated.
Here is picture of db

enter image description here

How to&Answers:

Your condition doesn’t make sense.

Lets say that the user picked enable -> $_POST['getval'] = 1;

Your query would be:

Update {table} SET requests = 1 WHERE requests = 1

  • Since none of the records have a value of 1 in the requests column, that condition would never exist and the update won’t happen.
  • Even if there were rows with “requests = 1”, the update won’t really change them as their value is already 1.
  • The same goes for the case where the user picks “disable” (0)

I believe you should update your condition to a specific row.
You can do it by adding a hidden input to the form with the specific row you wish to update. And update your condition to so it would be something like:

"id" => $_POST['row_id']