简体   繁体   English

在 PHP 中只更新/插入一列数据库表

[英]Update/insert only a column of database table in PHP

I WordPress table named wp_fes_vendors, there is a total of 12 columns.我的 WordPress 表名为 wp_fes_vendors,一共有 12 列。

Out of these 12 columns, I want to only update the data of column name requests在这 12 列中,我只想更新列名请求的数据

The data i am getting for this column is from a custom form in backend stored in $_POST['getval']我为此列获取的数据来自存储在$_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 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这是db的图片

在此处输入图片说明

Your condition doesn't make sense.你的条件没有意义。

Lets say that the user picked enable -> $_POST['getval'] = 1;假设用户选择了enable -> $_POST['getval'] = 1;

Your query would be:您的查询将是:

Update {table} SET requests = 1 WHERE requests = 1更新{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.由于请求列中没有任何记录的值为 1,因此该条件永远不会存在并且不会发生更新。
  • Even if there were rows with "requests = 1", the update won't really change them as their value is already 1.即使有“requests = 1”的行,更新也不会真正改变它们,因为它们的值已经是 1。
  • The same goes for the case where the user picks "disable" (0)用户选择“禁用”(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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM