如果我尝试在 POST 提交中访问的密钥为空或未找到,我该如何处理?
我当前的代码:
$data = array(
'harga_jual' => $this->input->post('harga_jual') == '' ? NULL : $this->input->post('harga_jual')
);
如果在负载中未找到访问的元素,CodeIgniter 的
post()
类中的 Input
方法将返回 null
值(默认为 null
)。
因此,您不需要在脚本中执行任何其他操作——只需享受帮助器方法的行为即可。
在 CI 项目中搜索
function _fetch_from_array(
就可以在源代码中看到。
$data = [
'harga_jual' => $this->input->post('harga_jual')
];
如果您将
$data
传递到视图,并且 $this->input->post('harga_jual')
未提交或为 null
,则 $harga_jual
将在视图中包含 null
。
或者如果您的 php 版本 >= 7.0,您可以使用 本文中的 Null Coalescing Operator。
<?php
// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';
// This is equivalent to:
$username = isset($_GET['user']) ? $_GET['user'] : 'nobody';
// Coalescing can be chained: this will return the first
// defined value out of $_GET['user'], $_POST['user'], and
// 'nobody'.
$username = $_GET['user'] ?? $_POST['user'] ?? 'nobody';
?>
您需要将
null
放在引号中。您可以尝试以下方法-
$harga_jual = $this->input->post('harga_jual') ? $this->input->post('harga_jual') : 'null'; //you can use $_POST['harga_jual'] also
$data = array('harga_jual' => $harga_jual);
您可以使用 is_null() 来检查 POST 值是否为 null。
$data = array(
'harga_jual' => is_null($this->input->post('harga_jual')) ? NULL : $this->input->post('harga_jual')
);