如果在使用 $this->input->post() 时在 $_POST 中找不到值,则将值声明为 null



我应该如何处理我尝试在 POST 提交中访问的密钥为空或找不到的情况?

我当前的代码:

$data = array(
'harga_jual' => $this->input->post('harga_jual') == '' ? NULL : $this->input->post('harga_jual')
);

如果找不到有效负载中访问的元素,CodeIgniterInput类中的post()方法将返回一个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,你可以使用本文中的空合并运算符。

<?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 值是否为空。

$data = array(
'harga_jual' => is_null($this->input->post('harga_jual')) ? NULL : $this->input->post('harga_jual')
);

最新更新