我正在使用Codeigniter 3,PHP和MySQL。
我试图从MySQL数据库中选择一条记录,并根据结果运行更新查询。
applications.application_id = NullableCInt(txtAppID.Text)
到目前为止我的代码是;
If result = 0, update.
If result = 1, do nothing.
数据在我的数据库中更新是否有任何原因?我没有收到任何错误消息。
任何帮助都将不胜感激。
答案 0 :(得分:1)
$query->result()
returns an array of objects where each object is a row from the table. (As you can see in the var_dump in your comments)
Without other changes your conditional should be
if($result->g_data == '0') { ...
That said, you should have checked earlier in the method that the database atually returned results. Also, you don't need more than one row so don't use result()
use 'row()' instead
...
$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 you do the above then the conditional can remain as you have it coded
if($result == '0') {...
答案 1 :(得分:0)
执行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函数作为值传递。