Multiple upload in Cakephp 3.0 - cakephp-3.0

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!'));
}
}
}
}

Related

How to post form data with ignoring the default value on a column in database

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);
}
}

Join table and display

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>

Zend update() gives out application error even with correct parameters

I am using Zend_File_Transfer_Adapter_HTTP() to upload a file (image) and then with Application_Model_DbTable_User() to update the users mysql table with the corresponding path of the file .
This is the action in the controller :
public function profileAction() {
$form = new Application_Form_Updateprofile();
$users = new Application_Model_DbTable_User();
$session = new Zend_Auth_Storage_Session();
$adapter = new Zend_File_Transfer_Adapter_HTTP();
$loggedUser = $session->read()->username;
$this->view->form = $form;
if ($this->getRequest()->isPost()) {
$adapter->setDestination('ProfilePhotos');
$filename = pathinfo($form->image->getFileName());
$adapter->addFilter('Rename', uniqid() . '.' . $filename['extension']);
if (!$adapter->receive()) {
$messages = $adapter->getMessages();
echo implode("\n", $messages);
} else {
$userProfilePhoto = $adapter->getFileName('image');
$users->UpdateProfilePic($loggedUser, $userProfilePhoto);
}
}
}
This is the function UpdateProfilePic() in the Zend_File_Transfer_Adapter_HTTP() :
public function UpdateProfilePic($username, $img_address) {
$bind = array("profile_pic" => $img_address);
$where = "username = $username";
$this->_db->update($this->_name, $bind, $where);
}
Var_dump($username,$img_address,$bind,$where)
Output :
$img_address - string(31) "ProfilePhotos\5429294234ebe.gif"
$username - string(7) "Tiberiu"
$bind - array(1) { ["profile_pic"]=> string(31) "ProfilePhotos\5429294234ebe.gif" }
$where - string(18) "username = Tiberiu"
Users table :
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email` varchar(255) NOT NULL,
`username` varchar(30) NOT NULL,
`password` varchar(15) DEFAULT NULL,
`profile_pic` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1
This is my first attempt on Zend_File_Upload and although the file transfer is a success it won't update the users table and I can't figure out why , I've checked the manual and I think I'm feeding the correct parameters to the update() action.
The mistake was in UpdateProfilePic() function in my db class .
It should be :
$where = "`username` = '$username'";
Instead of :
$where = "`username` = $username";

MySQL Decimal empty string / null (Meekrodb)

I have the following table:
CREATE TABLE `Plot` (
`idPlot` int(11) NOT NULL,
`ListPrice` decimal(9,2) DEFAULT NULL,
`WebPrice` decimal(9,2) DEFAULT NULL,
`BottomPrice` decimal(9,2) DEFAULT NULL,
PRIMARY KEY (`idPlot`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
I want to have values stored an NULL in the decimal fields if an empty string is passed. I can only seem to store 0.00 however.
I'm using Meekrodb to do the update:
$db->update('Plot', array(
'ListPrice' => $one['ListPrice'],
'BottomPrice' => $one['BottomPrice'],
'WebPrice' => $one['WebPrice']
), "idPlot=%s", $one['idPlot']);
My input array looks like this:
Array
(
[idPlot] => 6
[ListPrice] => 99,999.00
[BottomPrice] =>
[WebPrice] =>
)
Meekro runs:
UPDATE `Plot` SET `ListPrice`='99999.00', `BottomPrice`='', `WebPrice`='' WHERE idPlot='6'
And I get:
Array
(
[0] => Array
(
[idPlot] => 6
[ListPrice] => 99999.00
[WebPrice] => 0.00
[BottomPrice] => 0.00
)
)
stored in the database.
Is there any way of making it populate the fields with NULL rather than 0.00???
Thanks
Please note the difference between an empty string:
$foo = '';
... and a NULL value:
$foo = NULL;
The print_r() function does not display the difference; you need to use var_dump() to accurately dump your variables:
$data = array('', NULL);
print_r($data);
var_dump($data);
Array
(
[0] =>
[1] =>
)
array(2) {
[0]=>
string(0) ""
[1]=>
NULL
}
I believe you have to insert the value as NULL without quotations

SQLSTATE[HY000]: General error: 1366 Incorrect integer value:

$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);