【问题标题】:Codeigniter Select and (conditional) Update QueryCodeigniter 选择和(有条件的)更新查询
【发布时间】:2017-09-01 17:04:46
【问题描述】:

我正在使用 Codeigniter 3、PHP 和 MySQL。

我正在尝试从 MySQL 数据库中选择一条记录,并根据结果运行更新查询。

If result = 0, update.
If result = 1, do nothing.

到目前为止我的代码是;

public function addData($itemId) {
    $gDescription = 'test';
    $gPreviewLink = 'test';
    $gThumbnail = 'test';
    $gPageCount = 'test';

    $this->db->select('g_data');
    $this->db->from('item');
    $this->db->where('item_id', $itemId);
    $query = $this->db->get();
    $result = $query->result(); 
    // var_dump($result) returns array(1) { [0]=> object(stdClass)#22 (1) { ["g_data"]=> string(1) "0" } }

        $data = array(
        'item_description'  => $gDescription,
        'item_preview_link' => $gPreviewLink,
        'item_thumbnail'    => $gThumbnail,
        'item_pageCount'    => $gPageCount,
        'g_data'            => '1',
        'g_data_timestamp'  => 'NOW()'
        );
        // if result = 0 update
        if($result == '0') {
        $this->db->where('item_id',$itemId);
        $this->db->update('item', $data);
    }
        }

我的数据库中的数据不会更新有什么原因吗?我没有收到任何错误消息。

任何帮助将不胜感激。

【问题讨论】:

  • 你实际上并没有在这里问过问题......
  • $result 是数字还是字符?顶部示例显示数字,但您 == 到字符“0”

标签: php mysql codeigniter


【解决方案1】:

$query->result() 返回一个对象数组,其中每个对象都是表中的一行。 (如您在 cmets 中的 var_dump 中所见)

如果没有其他更改,您的条件应该是

if($result->g_data == '0') { ...

也就是说,您应该早先检查数据库最终返回结果的方法。此外,您不需要超过一排,所以不要使用 result() 而是使用 'row()'

...
$query = $this->db->get();
// The following will set $result to the value of "g_data" if there 
// are rows and to "0" if there are none.
$result = $query->num_rows() > 0 ? $query->row()->g_data: '0';
...

如果您执行上述操作,则条件可以保持原样

if($result == '0') {...

【讨论】:

    【解决方案2】:

    执行 SELECT 查询意味着对数据库进行不必要的额外访问。只需将您的 0 标准构建到您的 UPDATE 查询中 - 如果不满足,则不会影响任何行。

    代码:

    $data = [
        'item_description'  => $gDescription,
        'item_preview_link' => $gPreviewLink,
        'item_thumbnail'    => $gThumbnail,
        'item_pageCount'    => $gPageCount,
        'g_data'            => '1'
    ];
    
    $this->db->where([
        'item_id' => $itemId,
        'g_data'  => 0
    ]);
    $this->db->set('g_data_timestamp', 'NOW()', false);
    $this->db->update('item', $data);
    // return (bool)$this->db->affected_rows();
    

    全部在一个查询执行中完成。我还冒昧地演示了如何使用set() 的第三个参数将 MySQL 函数作为值传递。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-02-02
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 2011-09-18
      • 2018-09-22
      • 2016-01-16
      • 1970-01-01
      相关资源
      最近更新 更多