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

u7up0aaq  于 8个月前  发布在  其他
关注(0)|答案(4)|浏览(54)

我应该如何处理我在POST提交中试图访问的键为null或找不到的情况?
当前代码:

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

3lxsmp7m1#

CodeIgniter的Input类中的post()方法将返回一个null值,如果在你的有效负载中没有找到被访问的元素(默认值为null)。
由于这个原因,您不需要在脚本中执行任何额外的操作--只需享受helper方法的行为。
如果在CI项目中搜索function _fetch_from_array(,您可以在源代码中看到。

$data = [
    'harga_jual' => $this->input->post('harga_jual')
];

如果您将$data传递给视图,而$this->input->post('harga_jual')未提交或为null,则$harga_jual将在视图中包含null

mrwjdhj3

mrwjdhj32#

或者如果你的php版本>= 7.0,你可以使用this article中的空合并运算符。

<?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';
?>
lc8prwob

lc8prwob3#

您需要将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);
hmae6n7t

hmae6n7t4#

你可以使用is_null()来检查POST值是否为null。

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

相关问题