gpt4 book ai didi

php - Codeigniter 选择和(有条件的)更新查询

转载 作者:行者123 更新时间:2023-11-28 23:17:25 25 4
gpt4 key购买 nike

我正在使用 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);
}
}

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

如有任何帮助,我们将不胜感激。

最佳答案

$query->result() 返回一个对象数组,其中每个对象都是表中的一行。 (正如您在评论中的 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') {...

关于php - Codeigniter 选择和(有条件的)更新查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43259035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com