如果没有数据,如何选择NULL;如果存在,如何显示数据? [英] How to select NULL if there are no data and display the data if it exist?
问题描述
我想从MySQL数据库中选择AS NULL.这是选择查询:
I'd like to do a select AS NULL from MySQL db. This is the select query:
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);
}
当我在视图上使用它时:
And when I use this on the view:
<?php echo $record->name; ?>
我很高兴得到Trying to get property of non-object error
.该如何解决?
I kepp getting Trying to get property of non-object error
. How to solve this?
我的表结构:
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
推荐答案
如果表为空(0行),则查询结果= null通常为
If table is empty (0 rows), the query result = null is normally.
要在存在行ID x时显示行数据,应选择列而不是select NULL AS column
,因为如果存在行数据,则所有列的值永远为空.
And you want to show row data when row ID x is exists, you should be select column, not select NULL AS column
, because if row data is exists, all column value is null forever.
因此,将代码更改为SQL时不要选择null,并且当查询结果为空时,将返回默认设置,如下所示:
So, change code to SQL do not select null, and when query result is empty, return a default sets, like this:
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;
}
这篇关于如果没有数据,如何选择NULL;如果存在,如何显示数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!