如果没有数据,如何选择NULL并显示数据(如果存在)?

时间:2017-02-13 03:00:14

标签: php mysql json codeigniter

我想从MySQL db中选择一个AS NULL。这是选择查询:

function get_new()
{
    $query = "SELECT DATE_FORMAT(curdate(),'%d/%m-%Y') AS date_created, NULL AS name, NULL AS address, NULL AS status FROM t_penomoran";
    $result = $this->db->query($query)->row();

    return $result;
}

这是控制器

public function add()
{
    $id         = 0;
    $master     = $this->MPenomoran->get_new();

    $data = array (
        'titlepage'     => APP_TITLEPAGE,
        'titleapp'      => 'Penomoran',
        'userid'        => $this->session->userdata('nip'),
        'id'            => $id,
        'record'        => $master,
        'error'         => '',
        'complete'      => 'true',
        'loadmethod'    => 'add',
        'contentpage'   => 'penomoran/detail');

    $this->load->view('shared/master_app', $data);
}

当我在视图上使用它时:

<?php echo $record->name; ?>

我知道Trying to get property of non-object error。怎么解决这个问题?

我的表结构:

CREATE TABLE `t_penomoran` (
`nomor` int(50) NOT NULL,
`date_created` date DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
`jenis_pekerjaan` text,
`nominal` bigint(20) DEFAULT NULL,
`address` varchar(50) DEFAULT NULL,
`pic` varchar(100) DEFAULT NULL,
`keterangan` varchar(255) DEFAULT NULL,
`status` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin

4 个答案:

答案 0 :(得分:1)

您可以在选择查询中使用mysql if-else,例如 -

SELECT DATE_FORMAT(curdate(),'%d/%m-%Y') AS date_created, 
    IF(name IS NULL, '', name) AS name, 
    IF(address IS NULL, '', address) AS address, 
    IF(status IS NULL, '', status) AS status 
FROM t_penomoran

我执行了查询,它给出了如下所述的结果,没有任何错误 -

date_created | name | address | status
13/02-2017   |      |         | 1

希望这会对你有所帮助。

答案 1 :(得分:1)

如果table为空(0行),则查询结果= null通常为。

并且您希望在存在行ID x时显示行数据,您应该选择列而不是select NULL AS column,因为如果存在行数据,则所有列值永远为空。

因此,将代码更改为SQL不会选择null,并且当查询结果为空时,返回默认设置,如下所示:

function get_data( $id )
{
    $query = "SELECT
            DATE_FORMAT(curdate(),'%d/%m-%Y') AS date_created,
            `name`,
            `address`,
            `status`
        FROM `t_penomoran`
        WHERE `nomor` = '{$id}'";

    $result = $this->db->query($query)->row();

    if ( empty($result) ) {
        $result = (object)[
            'date_created' => date('d/m-Y'),
            'name' => null,
            'address' => null,
            'status' => null,
        ];
    }

    return $result;
}

答案 2 :(得分:1)

如果你这样做会怎么样......

if (empty($record->name)) { echo "Name"; }

答案 3 :(得分:0)

你的问题不是NULL as field,它是:

$query = "SELECT DATE_FORMAT(curdate(),'%d/%m-%Y') AS date_created, NULL AS name, NULL AS address, AS status FROM t_penomoran";

address, AS status

这里和AS之间没有任何内容。