I am using the Yii PHP framework, trying to display user_comment and user_reply from two tables who both have a column named comment_id.
This is the comment table
CREATE TABLE `comment` (
`comment_id` int(11) NOT NULL,
`byy` varchar(30) NOT NULL,
`user_comment` varchar(900) NOT NULL,
`topic_id` varchar(30) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`up` bigint(11) NOT NULL,
`down` bigint(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
This is the reply table
CREATE TABLE `reply` (
`reply_id` int(11) NOT NULL,
`comment_id` int(19) NOT NULL,
`byy` varchar(29) NOT NULL,
`user_reply` varchar(29) NOT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`up` varchar(29) NOT NULL,
`down` varchar(29) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I want to display user_comment and user_reply in a list view format, sorted according to the comment_id. I am having problems with that.
<?php
$querys = new Query;
$querys->select([
'comment.user_comment',
'reply.user_reply']
)
->from('comment')
->join('LEFT OUTER JOIN', 'reply',
'reply.comment_id =comment.comment_id') ;
$command = $querys->createCommand();
$data = $command->queryAll();
$queryd = new Query;
$queryd->select([
'comment.user_comment',
'reply.user_reply']
)
->from('comment')
->join('LEFT OUTER JOIN', 'reply',
'reply.comment_id =comment.comment_id')
->LIMIT(5);
$command = $queryd->createCommand();
$data = $command->queryAll();
foreach ($data as $detail) {
$dataArr[] = array(
'user_reply' => $detail['user_reply']
);
}
$dataProvider = new ArrayDataProvider([
'allModels' => $dataArr,
'pagination' => [
'pageSize' => 10,
],
'sort' => [
'attributes' => ['comment_created_at'],
],
]);
echo ListView::widget([
'dataProvider' => $dataProvider,
'itemOptions' => ['class' => 'comment-item'],
'itemView' => 'adapter',
]);
?>
Adapter class
<?php
use yii\helpers\Html;
use yii\helpers\HtmlPurifier;
//var_dump($model);exit;
?>
<div class="col-lg-12 col-sm-12">
<section>
<?php echo $model['user_reply']; ?>
</section>
</div>
I am getting this error:
Getting unknown property: Undefined index: user_reply
What am I doing wrong?
Try
foreach ($data as $detail) {
$dataArr[] = array(
'user_reply' => $detail['reply.user_reply']
);
}
or use alias
$queryd = new Query;
$queryd->select('comment.user_comment as user_comment,
reply.user_reply as user_reply')
->from('comment')
->join('LEFT OUTER JOIN', 'reply',
'reply.comment_id =comment.comment_id')
->LIMIT(5);
$command = $queryd->createCommand();
$data = $command->queryAll();
foreach ($data as $detail) {
$dataArr[] = array(
'user_reply' => $detail['user_reply']
);
}
and for dataProvider you must remeber there is a models collection then
<div class="col-lg-12 col-sm-12">
<section>
<?php
foreach($models as $model){
//echo $model['user_reply'];
echo $model->user_reply;
}
?>
</section>
</div>
Related
I want to create registration form but I need id_role to be static value for this form but the I couldn't insert data with this form because of that. I can do it manually from phpmyadmin with default value was already set but I cannot do that from codeigniter
I've tried to make it to be dropdown again and choose the id_role manually and it was working but I want to make every user who wants to register with this form has the same id_role value
This is the role table
CREATE TABLE `role` (
`id` INT(11) NOT NULL,
`role` VARCHAR(50) NOT NULL,
PRIMARY KEY (`id`)
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
;
This is the orang_tua table. As you can see it has default value 3
CREATE TABLE `orang_tua` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`n_ibu` VARCHAR(100) NOT NULL,
`n_ayah` VARCHAR(100) NOT NULL,
`email` VARCHAR(100) NOT NULL,
`no_tlp` VARCHAR(20) NOT NULL,
`alamat` VARCHAR(100) NOT NULL,
`id_siswa` INT(11) NOT NULL,
`id_role` INT(1) NOT NULL DEFAULT 3,
`pass` VARCHAR(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `email_ot` (`email`),
INDEX `FK_orang_tua_siswa` (`id_siswa`),
INDEX `FK_orang_tua_role` (`id_role`),
CONSTRAINT `FK_orang_tua_role` FOREIGN KEY (`id_role`) REFERENCES `role` (`id`) ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT `FK_orang_tua_siswa` FOREIGN KEY (`id_siswa`) REFERENCES `siswa` (`id`) ON UPDATE CASCADE ON DELETE CASCADE
)
COLLATE='latin1_swedish_ci'
ENGINE=InnoDB
AUTO_INCREMENT=12
;
This is the view for registration form and I want to make it automatic to choose 3 or if I can delete this role dropdown so every user don't need to choose anymore
<div class="input-group">
<span class="input-group-addon">
<i class="material-icons">people</i>
</span>
<div class="form-line">
<select name="id_role" class="form-control ms">
<option value="">-Login Sebagai-</option>
<?php
foreach ($all_role as $role) {
$selected = ($role['id'] == $this->input->post('id_role')) ? ' selected="selected"' : "";
echo '<option value="' . $role['id'] . '" ' . $selected . '>' . $role['role'] . '</option>';
}
?>
</select>
</div>
</div>
This is controllers for registration form
function daftarortu()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('pass', 'Pass', 'required|trim');
$this->form_validation->set_rules('pass1', 'Confirm Pass', 'required|trim|matches[pass]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
$this->form_validation->set_rules('no_tlp', 'No Tlp', 'required|trim');
$this->form_validation->set_rules('alamat', 'Alamat', 'required|trim');
$this->form_validation->set_rules('n_ayah', 'N Ayah', 'required|trim');
$this->form_validation->set_rules('n_ibu', 'N Ibu', 'required|trim');
$this->form_validation->set_rules('id_role', 'Id Role', 'required');
$this->form_validation->set_rules('id_siswa', 'Id Siswa', 'required');
if ($this->form_validation->run()) {
$params = array(
'id_siswa' => $this->input->post('id_siswa'),
'id_role' => $this->input->post('id_role'),
'pass' => md5($this->input->post('pass')),
'n_ibu' => $this->input->post('n_ibu'),
'n_ayah' => $this->input->post('n_ayah'),
'email' => $this->input->post('email'),
'no_tlp' => $this->input->post('no_tlp'),
'alamat' => $this->input->post('alamat'),
);
$orang_tua_id = $this->Register_model->reg_orang_tua($params);
redirect('login');
} else {
$this->load->model('Siswa_model');
$data['all_siswa'] = $this->Siswa_model->get_all_siswa();
$this->load->model('Role_model');
$data['all_role'] = $this->Role_model->get_all_role();
$data['_regis'] = 'register/daftarortu';
$this->load->view('layouts/reg', $data);
}
}
This is model for registration form
function reg_orang_tua($params)
{
$this->db->insert('orang_tua', $params);
return $this->db->insert_id();
}
I wanted to make automatic value which is 3 for this form for id_role column and so the role is consistent on 3 for new user who wants to register
Remove select box with name "id_role".
Update your controller function as below.
function daftarortu()
{
$this->load->library('form_validation');
$this->form_validation->set_rules('pass', 'Pass', 'required|trim');
$this->form_validation->set_rules('pass1', 'Confirm Pass', 'required|trim|matches[pass]');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email|trim');
$this->form_validation->set_rules('no_tlp', 'No Tlp', 'required|trim');
$this->form_validation->set_rules('alamat', 'Alamat', 'required|trim');
$this->form_validation->set_rules('n_ayah', 'N Ayah', 'required|trim');
$this->form_validation->set_rules('n_ibu', 'N Ibu', 'required|trim');
$this->form_validation->set_rules('id_role', 'Id Role', 'required');
$this->form_validation->set_rules('id_siswa', 'Id Siswa', 'required');
if ($this->form_validation->run()) {
$params = array(
'id_siswa' => $this->input->post('id_siswa'),
'id_role' => 3,
'pass' => md5($this->input->post('pass')),
'n_ibu' => $this->input->post('n_ibu'),
'n_ayah' => $this->input->post('n_ayah'),
'email' => $this->input->post('email'),
'no_tlp' => $this->input->post('no_tlp'),
'alamat' => $this->input->post('alamat'),
);
$orang_tua_id = $this->Register_model->reg_orang_tua($params);
redirect('login');
} else {
$this->load->model('Siswa_model');
$data['all_siswa'] = $this->Siswa_model->get_all_siswa();
$this->load->model('Role_model');
$data['all_role'] = $this->Role_model->get_all_role();
$data['_regis'] = 'register/daftarortu';
$this->load->view('layouts/reg', $data);
}
}
Hi I'm a beginner in CakePHP 3.0 my I have a problem, it won't save in database.
Controller:
public function add() {
$myTable = TableRegistry::get('Files');
$data = $this->request->getData();
$file = $myTable->newEntities($data);
if ($this->request->is('post')) {
foreach ($file as $key => $val) {
$val['user_id'] = $this->Auth->user('id');
$val['filename'] = $_FILES['photo']['name'];
$val['file_location'] = '../uploads/files/';
$val['file_type'] = $_FILES['photo']['type'];
$val['file_size'] = $_FILES['photo']['size'];
$val['file_status'] = 'Active';
$val['created'] = date("Y-m-d H:i:s");
$val['modified'] = date("Y-m-d H:i:s");
if($myTable->save($val)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
} else {
$this->Flash->error(__('File not upload!'));
}
}
}
}
can someone help me to fixed my problem, I followed the docs in CakePHP but it seems not working.
Views:
<?= $this->Form->create(null, ['type' => 'file', 'url' => ['controller' => 'Files', 'action' => 'add']]) ?>
echo $this->Form->input('photo[]', ['type' => 'file','multiple' => 'true','label' => 'Upload Multiple Photos']);
This is my database structure:
CREATE TABLE `files` (
`id` int(8) NOT NULL,
`user_id` varchar(100) NOT NULL,
`filename` varchar(100) NOT NULL,
`file_location` varchar(1000) NOT NULL,
`file_type` varchar(100) NOT NULL,
`file_size` varchar(100) NOT NULL,
`file_status` varchar(100) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
public function add() {
$myTable = TableRegistry::get('Files');
if ($this->request->is('post')) {
foreach ($_FILES['photo'] as $key => $file) {
$val['user_id'] = $this->Auth->user('id');
$val['filename'] = $file['name'];
$val['file_location'] = '../uploads/files/';
$val['file_type'] = $file['type'];
$val['file_size'] = $file['size'];
$val['file_status'] = 'Active';
$val['created'] = date("Y-m-d H:i:s");
$val['modified'] = date("Y-m-d H:i:s");
$val = $myTable->newEntity($val);
//Make some count here to trace the no of files uploaded and take this if else out of this foreach, otherwise it will display many flash message.
if($myTable->save($val)) {
$this->Flash->success(__('File has been uploaded and inserted successfully.'));
} else {
$this->Flash->error(__('File not upload!'));
}
}
}
}
In my database, my table has the following structure:
CREATE TABLE `tbl_app_versions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`app` varchar(100) DEFAULT NULL,
`version` varchar(50) DEFAULT NULL,
`force_update` bit(1) DEFAULT NULL,
`is_active` bit(1) DEFAULT NULL,
`created` datetime DEFAULT NULL,
`modified` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
Note that 'force_update' is bit. It can be either 1 or 0.
In my code, I fetch the data and want to see if the value is 1 or 0. CakePHP for some reason returns the following in either case:
Array
(
[0] => Array
(
[Platforms] => Array
(
[id] => 1
[app] => ios
[version] => 1.0.042
[force_update] =>
[is_active] =>
[created] =>
[modified] =>
)
)
[1] => Array
(
[Platforms] => Array
(
[id] => 2
[app] => android
[version] => 1.0.041
[force_update] =>
[is_active] =>
[created] =>
[modified] =>
)
)
)
Regardless of it's value, force_update shows the same. I'm using bit in most of my tables and I have to be able to do this check.
This:
<?php echo ($value['Platforms']['force_update']) ? 'Yes' : 'No'; ?>
Or:
<?php echo ($value['Platforms']['force_update'] = TRUE) ? 'Yes' : 'No'; ?>
Or:
<?php echo ($value['Platforms']['force_update'] == TRUE) ? 'Yes' : 'No'; ?>
all result in the same despite the fact that my data is:
'1', 'ios', '1.0.042', '0', '1', NULL, NULL
'2', 'android', '1.0.041', '1', '1', NULL, NULL
When using bit in database, if field is NULL, it returns FALSE, otherwise it returns TRUE.
So if it has any value in the field (1 or 0) it still returns TRUE.
Solution:
Change the field from bit to tinyint.
OR
On data manipulation, NULL the field in terms of FALSE and give it a value in terms of TRUE. This way every time I read the data it's either NULL or has a value, then based on that I can show the proper message in the views.
You could switch from bit to tinyint (1) but I think your if statement is wrong.
Try
<?php echo (!empty($value['Platforms']['force_update'])) ? 'Yes' : 'No'; ?>
empty() will catch botch NULL and 0 as 'No' and only 1 as 'yes'.
I am joining two tables tbl_complain_type and tbl_section.The sql for that tables are
CREATE TABLE IF NOT EXISTS `tbl_complain_type` (
`id` int(9) NOT NULL,
`section_id` varchar(250) NOT NULL,
`complains` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;
-- --------------------------------------------------------
--
-- Table structure for table `tbl_section`
--
CREATE TABLE IF NOT EXISTS `tbl_section` (
`id` int(9) NOT NULL,
`section` varchar(250) CHARACTER SET latin1 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=8 ;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `tbl_complain_type`
--
ALTER TABLE `tbl_complain_type`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `tbl_section`
--
ALTER TABLE `tbl_section`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `tbl_complain_type`
--
ALTER TABLE `tbl_complain_type`
MODIFY `id` int(9) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=20;
--
-- AUTO_INCREMENT for table `tbl_section`
--
ALTER TABLE `tbl_section`
MODIFY `id` int(9) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=8;
tbl_complain_type and tbl_section have relation like tbl_section.id=tbl_complain_type.section_id .
I have made relation in ComplainType model as
public function getSection()
{
return $this->hasMany(Section::className(), ['id' => 'section_id']);
}
and in section model as
public function getComplainType()
{
return $this->hasOne(ComplainType::className(), ['id' => 'section_id']);
}
and I have modified ComplainTypeSearch model as
public function search($params) {
$query = ComplainType::find() ;
$dataProvider = new ActiveDataProvider([
'query' => $query,
]);
$dataProvider->setSort([
'attributes' => [
'id',
'complains' => [
'asc' => ['complains' => SORT_ASC, 'complains' => SORT_ASC],
'desc' => ['complains' => SORT_DESC, 'complains' => SORT_DESC],
'label' => 'complains',
'default' => SORT_ASC
],
'section' => [
'asc' => ['tbl_section.id' => SORT_ASC],
'desc' => ['tbl_section.id' => SORT_DESC],
'label' => 'Section'
]
]
]);
if (!($this->load($params) && $this->validate())) {
$query->joinWith(['section']);
return $dataProvider;
}
$this->addCondition($query, 'id');
$this->addCondition($query, 'complains', true);
$this->addCondition($query, 'section_id');
return $dataProvider;
}
So in my index function, to display section with section name instead of section_id
I had to write as
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
['attribute' => 'section',
'label'=>'section',
'format' => 'raw',
'value'=>function ($data) {
return $data['section'][0]->section ;
}, 'filter' => true,
],
'complains',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
while
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'section',
,
'complains',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
doesnt print section in view file. Is there any better way than using
$data['section'][0]->section ; to display the section ? I think using $data['section'][0]->section is not the right way. I would like to hear some suggestions or better way to achieve this.
You are only showing the first section, if the records has multiple sections it will show only the first section. if it has no section then you should see an error. Probably you should do something like this
[
'attribute' => 'section',
'label'=>'section',
'format' => 'raw',
'value'=>function ($model) {
$sections = [];
if($model->section) {
foreach($model->section as $section) {
$sections[] = $section->section
}
}
return implode(', ', $sections);
},
'filter' => true,
],
$order = new Application_Model_DbTable_Order();
$orderno = $order->select()
->from($order, 'orderno')
->where('memberid = ?', $userid)
->order('orderno DESC')
->limit(1, 0);
SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'SELECT ordertable.orderno FROM ordertable WHERE (memberid = '30') ORDER BY orderno DESC LIMIT 1' for column 'orderno' at row 1
Got this error and am wondering if there is anything wrong with my code, because I have searched everywhere for the cause but don't seem to find any help.
#SQL code for Ordertable#
`orderno` int(5) NOT NULL AUTO_INCREMENT,
`memberid` int(5) DEFAULT NULL,
PRIMARY KEY (`orderno`)
#SQL code for Item#
`itemid` int(5) NOT NULL AUTO_INCREMENT,
`image` varchar(100) NOT NULL,
`itemname` varchar(30) DEFAULT NULL,
`description` varchar(100) DEFAULT NULL,
`itemtype` varchar(20) DEFAULT NULL,
PRIMARY KEY (`itemid`)
#SQL code for Orderdetail#
`orderdetailno` int(5) NOT NULL AUTO_INCREMENT,
`orderno` int(5) NOT NULL,
`itemid` int(5) NOT NULL,
`unitcost` decimal(6,2) DEFAULT NULL,
PRIMARY KEY (`orderdetailno`),
KEY `orderno` (`orderno`),
KEY `itemid` (`itemid`)
This is my sql code if it helps I'm using MySQL.
$request = new Zend_Session_Namespace('cart');
$auth = Zend_Auth::getInstance();
$user = $auth->getIdentity();
$userid = $user->userid;
$order = new Application_Model_DbTable_Order();
$itemdb = new Application_Model_DbTable_Item();
$orderdetail = new Application_Model_DbTable_Orderdetail();
$data = array ('memberid' => $userid);
$order->insert($data);
$orderno = $order->select()
->from($order, 'orderno')
->where('memberid = ?', $userid)
->order('orderno DESC')
->limit(1, 0);
foreach ($request->array as $var)
{
$unitprice = $itemdb->select()
->from('$itemdb', 'unitcost')
->where('itemid = ?', $var);
$newArray = array('orderno' => $orderno,
'itemid' => $var,
'unitcost' => $unitprice, );
$orderdetail->insert($newArray);
}
Any guidance will be very much appreciated.
Per https://stackoverflow.com/a/8882396/1432614, run
SELECT ##GLOBAL.sql_mode;
SELECT ##SESSION.sql_mode;
and if either include STRICT_TRANS_TABLES, remove it from the setting.
For example:
SET ##GLOBAL.sql_mode= 'NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
The reason you are getting that error is because you are attempting to use a Zend_Db_Select object as a value in your INSERT statement.
$orderno = $order->select()
->from($order, 'orderno')
->where('memberid = ?', $userid)
->order('orderno DESC')
->limit(1, 0);
And then inside the foreach loop:
$newArray = array('orderno' => $orderno, // <-- this becomes a SELECT statment
'itemid' => $var,
'unitcost' => $unitprice, );
$orderdetail->insert($newArray); // attempting to insert a select statement
You should execute the $orderno statement and fetch() the result if you want to use it in an insert statement:
$ordernum = $orderno->query()->fetch();
$newArray = array('orderno' => $ordernum,
'itemid' => $var,
'unitcost' => $unitprice, );
$orderDetail->insert($newArray);