i want casecading in cakephp. I am creating city manager where I have two things zones and states as a dropdown. if i select zone then states should come according to selected zone.please help me what should be the code for model view and controller.I am new in cakephp. table for cities table is given below
CREATE TABLE IF NOT EXISTS `cities` (
`id` int(11) NOT NULL,
`zone_id` int(11) NOT NULL,
`state_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`code` varchar(255) NOT NULL,
`total_sample` int(11) NOT NULL,
`population` int(11) NOT NULL,
`is_active` tinyint(1) NOT NULL,
`created` datetime NOT NULL,
`modified` datetime NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cities`
--
INSERT INTO `cities` (`id`, `zone_id`, `state_id`, `name`, `code`, `total_sample`, `population`, `is_active`, `created`, `modified`) VALUES
(1, 2, 2, 'avadi', '15018', 10, 100, 1, '2016-10-03 00:00:00', '2016-10-03 00:00:00');
Please help me with code for controller, view and model.
You can do this by 2 ways
Using Chained javascript library. in this way you have to format dropdown. for doing this you can follow This Tutorial
By using Ajax request according to select Zone and State
For Option 2: Html
echo $this->Form->input('zone_id', ['options' => $zons, 'empty' => '','id'=>'zoneDropdown']);
echo $this->Form->input('state_id', ['options' => $state, 'empty' => '','id'=>'stateDropdown']);
echo $this->Form->input('city', ['options' => [], 'empty' => '','id'=>'cityDropdown']);
Ajax Script for Html
$('#zoneDropdown, #stateDropdown').on('change', function (evt) {
ZONE = $("#zoneDropdown").val();
STATE = $("#stateDropdown").val();
$.ajax({
type: "GET",
url: baseURL+"cities/getCitiesOptions/"+ZONE+"/"+STATE,
dataType: "json",
success : function(returnData) {
$("#cityDropdown").val(returnData);
}
});
});
and the controller Function need to add
Public function getCitiesOptions($zone_id=null, $state_id=null){
$conditions = [];
if (!empty($zone_id)) {
$conditions['Cities.zone_id'] = $zone_id;
}
if (!empty($state_id)) {
$conditions['Cities.state_id'] = $state_id;
}
$cities = $this->Cities->find('all',['conditions'=>$conditions])->all()->toArray();
// make Options for dorpdown
$html = '';
foreach ($cities as $key => $value) {
$html .= '<option value="'.$value['code'].'">'.$value['name'].'</option>';
}
return $html;
}
Related
I use Codeigniter 3.1.11 and have some code which makes one big query to MySQL with an array. The time of a query with a limit of 30000 is about 9 seconds.
How can I reduce the request time? Maybe by using some indexes on my table, or do you know another method? If I need to use indexes, what indexes would I need to use and how can I use these indexes in my query on Codeigniter?
Code from model:
function rows_update() {
$query = $this->db->order_by('rating', 'DESC')->get_where('members', 'game_rating_and_balance_update_last_time <= now() - INTERVAL 1 DAY', '30000', '0');
$arrUpdateBatchData = [];
while ($row = $query->unbuffered_row('array'))
{
// some code here
$arrUpdateData = [
'UserID' => $row['UserID'],
'game_vault_balance' => $new_game_vault_balance,
'game_available_balance' => $new_game_available_balance,
'rating' => $rating_member,
'game_rating_and_balance_update_last_time' => date('Y-m-d H:i:s')
];
$arrUpdateBatchData[] = $arrUpdateData;
if (count($arrUpdateBatchData) > 500)
{
$this->db->update_batch('members', $arrUpdateBatchData, 'UserID');
$arrUpdateBatchData = [];
}
}
//update last items
if (count($arrUpdateBatchData) > 0)
{
$this->db->update_batch('members', $arrUpdateBatchData, 'UserID');
$arrUpdateBatchData = [];
}
return;
}
Raw query to MySQL with update_batch (I simply write only one row from an array):
UPDATE members SET game_vault_balance = CASE WHEN UserID = '9915075' THEN 803.60516004772 ELSE game_vault_balance END, game_available_balance = CASE WHEN UserID = '9915075' THEN 4.1253850908788 ELSE game_available_balance END, rating = CASE WHEN UserID = '9915075' THEN 0.24 ELSE rating END, game_rating_and_balance_update_last_time = CASE WHEN UserID = '9915075' THEN '2020-07-24 22:00:36' ELSE game_rating_and_balance_update_last_time END WHERE UserID IN('9915075')
Table structure:
CREATE TABLE `members` (
`id` int(10) UNSIGNED NOT NULL,
`UserID` varchar(64) NOT NULL,
`telegram_id` varchar(64) DEFAULT NULL,
`first_name` varchar(64) DEFAULT NULL,
`last_name` varchar(64) DEFAULT NULL,
`language` varchar(64) DEFAULT NULL,
`currency` varchar(64) DEFAULT NULL,
`status` varchar(64) DEFAULT NULL,
`rating` varchar(64) DEFAULT NULL,
`game_vault_balance` decimal(32,8) DEFAULT 0.00000000,
`game_available_balance` decimal(32,8) DEFAULT 0.00000000,
`game_rating_and_balance_update_last_time` datetime DEFAULT NULL,
`updated` datetime DEFAULT NULL,
`created` datetime DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Indexes of this table:
ALTER TABLE `members`
ADD PRIMARY KEY (`id`),
ADD UNIQUE KEY `UserID` (`UserID`) USING BTREE;
AUTO_INCREMENT for the members table:
ALTER TABLE `members`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT;
COMMIT;
So I'm trying to find users from my database that don't have ANY rows in another table for the previous month, although it looks like my query is correct; I'm getting empty results?
public function __construct() {
parent::__construct();
//Set Payment Dates
$this->dates = array('1st', '8th', '15th', '25th');
//Which Month do the figures need submitting as
$this->monthPrev = date('F Y', strtotime(date('F Y')." -1 month"));
$this->currentMonth = date('F Y', strtotime('this month'));
}
public function getUnreportedQuarterlies()
{
$this->db->select('quarterly_figures.month, quarterly_figures.centre, users.name, users.email');
$this->db->from('quarterly_figures');
$this->db->join('users', 'users.name = quarterly_figures.centre', 'left');
$this->db->where("quarterly_figures.month", $this->monthPrev);
$this->db->where("quarterly_figures.centre IS NULL");
return $this->db->get()->result();
}
My database rows look something like so:
users
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`name` varchar(45) DEFAULT NULL,
`email` varchar(45) DEFAULT NULL,
`password` varchar(45) DEFAULT NULL,
`address` varchar(45) DEFAULT NULL,
`owners_password` varchar(45) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `users` (`id`, `name`, `email`, `password`, `address`, `owners_password`) VALUES
(1, 'Aldridge', 'aldridge#website.co.uk', 'password', '127.0.0.1', 'password');
quarterly_figures
CREATE TABLE `quarterly_figures` (
`id` int(11) NOT NULL,
`centre` varchar(45) DEFAULT NULL,
`month` varchar(45) DEFAULT NULL,
`date` date DEFAULT NULL,
`direct_debits` varchar(45) DEFAULT NULL,
`money_paid` varchar(45) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
INSERT INTO `quarterly_figures` (`id`, `centre`, `month`, `date`, `direct_debits`, `money_paid`) VALUES
(1, 'Rugby', 'January 2019', '2019-01-01', '128', '3519.00');
The 'user' table has no relation with the 'quarterly_figures' table , If there is no relation returned data is not possible. you can insert an users.id into 'quarterly_figures' for each input.
I would like to implement this like and unlike into codeigniter. I can do it in the normal php using the following codes but I just don't why it is not working in codeigniter below is my database table and my model view and controller. any help would be appritiated. thanks.
posts table
CREATE TABLE `posts` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`title` varchar(100) NOT NULL,
`content` text NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
like-unlike table
CREATE TABLE `like-unlike` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`post_id` int(11) NOT NULL,
`purpose` int(2) NOT NULL,
`timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Jquery file
function likeItem(post_id)
{
if ($("#likeItem_" + post_id).text() == "Like")
{
$("#likeItem_" + postid).html('Unlike');
var purpose = "Like";
} else
{
$("#likeItem_" + post_id).html('Like');
var purpose = "UnLike";
}
$.ajax({
type: "POST",
url: "<?php echo base_url('posts/likes');?>",
data: "postId=" + postId + "&purpose=" + purpose,
success: function (data)
{
// do seomthing here with data
// console.log(data) --> to see data return or not
}
}
);
This is my model "Post_model.php"
public function itemLike() {
$id = $this->session->userdata('user_id');
$postId = $this->input->post('post_id');
$purpose = $this->input->post('purpose');
if ($purpose == "Like") {
// echo 'test';
// exit();
$data = array(
"user_id" => $id,
"post_id" => $postId,
);
$this->db->insert('like', $data);
} else {
echo 'failed';
}
}
This is my view file
<li><a class="like-unlike" href="#" id="likeItem_{$item['post_id']}" onclick="likeItem({$item['post_id']})">Like</a></li>
This is my Controller "Post.php"
public function likeItem()
{
$this->usermodel->itemLike();
}
In your database schema, you have mentioned table like_unlike and you are saving data in to table like-unlike.
Also, you set column purpose for mandatory and you are not passing any values here:
$data = array(
"user_id" => $id,
"post_id" => $postId,
);
You don't need to pass data if you use default value. You also need to keep in mind that column purpose holds only integer value as per your database schema.
Apart from this you also need to modify code mention by #JYoThI
1st : Post name mismatch data : "postId=" + post_id + "&purpose=" + purpose,
$postId = $this->input->post('post_id');
change to
$postId = $this->input->post('postId');
2nd : pass the data like below and variable name is post_id not postId
data : {postId:postid,purpose:purpose},
Note : variable names are case sensitive take care about that .
I'm trying to insert some date to MySQL table with prepared insert with nested 3 nested selects in it. The thing is that for all nested selects a single variable is used. Actual SQL:
INSERT INTO db_test.offers
(`id`,`catalog_service_id`,`offer_name`,
`offer_description`,`offer_url`,
`offer_interaction_format`,`offer_methods`)
VALUES(1,
(SELECT `catalog_service_id` FROM db_test.catalog_services
WHERE `catalog_service_code` = ?),
(SELECT `catalog_service_name` FROM db_test.catalog_services
WHERE `catalog_service_code` = ?),
(SELECT `catalog_service_name` FROM db_test.catalog_services
WHERE `catalog_service_code` = ?),
'https://url.com', 'json', 'CC');
PHP code:
class test extends mysqli{
function db_action($host = null){
$mysqli = new mysqli($host, MYSQL_USER, MYSQL_PASS, "db_test");
if(!$mysqli){
die ("couldn't connect to mysql host" . mysqli_connect_error());
}
$codes= ["AAAAA005760000000001","ААААА032680000000001","ААААА032680000000002"];
$query="SQL code from above";
$stmt = $mysqli->prepare($query);
$stmt ->bind_param("sss", $offer, $offer, $offer);
foreach ($codes as $k => $offer) {
if($stmt->execute() === false){
print 'Wrong SQL. Error: ' . $stmt->error . "\r\n";
}else{
$last_inserted_id = $mysqli->insert_id;
print "Insert row with id: " . $last_inserted_id . " for service_code: ". $offer . "\r\n";
}
}
$stmt->close();
}
}
First iteration of foreach works fine (1 row is inserted with correct data), but on 2nd and 3rd (just for an example, real number of elements in $codes array is unknown). The The executed statement on the sql-server is executed with question marks instead of actual value. When I go through the function in debugger - the value of $offer var changes on each iteration of for each.
SQL error that comes from the server is obvious: catalog_service_id cannot be null.
table info:
CREATE TABLE `offers` (
`offer_id` int(11) NOT NULL AUTO_INCREMENT,
`id` int(11) NOT NULL,
`catalog_service_id` int(11) NOT NULL,
`offer_name` varchar(255) DEFAULT NULL,
`offer_description` varchar(1000) DEFAULT NULL,
`offer_create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`offer_start_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`offer_stop_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`offer_url` varchar(256) NOT NULL,
`offer_auth` enum('Basic','Digest') DEFAULT NULL,
`offer_auth_name` varchar(255) DEFAULT NULL,
`offer_auth_password` varchar(255) DEFAULT NULL,
`offer_auth_secret` varchar(255) DEFAULT NULL,
`offer_operator_id` int(11) NOT NULL,
`public_offer_url` varchar(1000) NOT NULL,
`offer_interaction_format` enum('urlencoded','json') NOT NULL DEFAULT 'urlencoded',
`offer_methods` enum('CC','MC') NOT NULL DEFAULT 'MC',
`offer_inn` varchar(20) DEFAULT NULL,
`offer_kpp` varchar(20) DEFAULT NULL,
`offer_min` int(11) DEFAULT NULL,
`offer_max` int(11) DEFAULT NULL,
PRIMARY KEY (`offer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8
I'm really stuck...
I have simple ralation tables : Each table (Agrement) 'umowas' have one item from table (Adult) 'rodzics' and one item from table (Children) 'dziecis'.
When call myaddress.com/cakephp/Umowas/add i do not see drop down menu for item 'rodzic_id' and 'dzieci_id' with its items names. I see only numer.
For example drop down menu for 'rodzic_id' shows Array(1=>1, 2=>2, 3=>3), not names of its record, like array( 1=>'Item name 1', 2=> 'Item name 2').....
Debug.log and Error.log is empty.
My query at bottm of screen is:
Nr Query Error Affected Num. rows Took (ms)
1 SELECTRodzic.idFROMakademia-uat.rodzicsASRodzicWHERE 1 = 1 2 2 3
2 SELECTDzieci.idFROMakademia-uat.dziecisASDzieciWHERE 1 = 1 1 1 2
My code is:
<?php
class UmowasController extends AppController {
var $name = 'Umowas';
var $scaffold;
var $helpers = array('Form' );
function index() {
$this->Umowa->recursive = 1;
$umowas = $this->Umowa->find('all');
$this->set('umowas', $umowas);
}
}
?>
-----------------------------------------
<?php
class RodzicsController extends AppController {
var $name = 'Rodzics';
var $scaffold;
function index() {
$this->Rodzic->recursive = 1;
$rodzics = $this->Rodzic->find('all');
$this->set('rodzics', $rodzics);
}
}
-------------------------------------------------------
<?php
class DziecisController extends AppController {
var $name = 'Dziecis';
var $scaffold;
function index() {
$this->Dzieci->recursive = 1;
$dziecis = $this->Dzieci->find('all');
$this->set('dziecis', $dziecis);
}
}
------------------------------------------
<?php
class Umowa extends AppModel {
var $name = 'Umowa';
public $belongsTo = array(
'Rodzic' => array(
'className' => 'Rodzic',
'conditions' => '',
'order' => '',
'foreignKey' => 'rodzic_id' //or your external key
),
'Dzieci' => array(
'className' => 'Dzieci',
'conditions' => '',
'order' => '',
'foreignKey' => 'dzieci_id' //or your external key
)
);
var $helpers = array('Form' );
function add() {
if (!empty($this->data)) {
$this->Umowa->create();
$this->Umowa->save($this->data);
$this->redirect(array('action'=>'index'));
}
$rodzics = $this->Umowa->Rodzic->generateList();
$this->set('rodzics', $rodzics);
$dziecis = $this->Umowa->Dzieci->generateList();
$this->set('dziecis', $dziecis);
}
}
?>
--------------------------------------------------------
<?php
class Rodzic extends AppModel
{
var $name = 'Rodzic';
var $hasMany = 'Umowa';
}
?>
-------------------------------------------------------
<?php
class Dzieci extends AppModel
{
var $name = 'Dzieci';
var $hasMany = 'Umowa';
}
?>
---------------------------------------------------------
view/Rodzics/add and do not exists
view/Umowas/add do not exists
view/Dziecis/add do not exist
`
My Tables is like this:
`
CREATE TABLE IF NOT EXISTS `dziecis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`imie_dziecka` varchar(18) DEFAULT NULL,
`nazwisko_dziecka` varchar(15) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
CREATE TABLE IF NOT EXISTS `rodzics` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`imie_rodzica` varchar(18) DEFAULT NULL,
`nazwisko_rodzica` varchar(15) DEFAULT NULL,
`telefon` int(9) DEFAULT NULL,
`adres_email` varchar(50) DEFAULT NULL,
`ulica` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `umowas` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`warunek_umowy` varchar(2048) DEFAULT NULL,
`data_rozwiazania_warunku` date DEFAULT NULL,
`data_zawarcia_umowy` date DEFAULT NULL,
`data_zerwania_umowy` date DEFAULT NULL,
`nr_umowy` int(4) DEFAULT NULL,
`rok_szkolny` int(4) DEFAULT NULL,
`wizerunek` varchar(3) DEFAULT NULL,
`miesiac_rozpoczecia_platnosci` int(2) DEFAULT NULL,
`raty` varchar(3) NOT NULL,
`utworzono` date NOT NULL,
`modyfikacja` date NOT NULL,
`zabezpieczona` varchar(3) NOT NULL,
`wydrukowana` varchar(3) NOT NULL,
`dzieci_id` int(11) NOT NULL,
`rodzic_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`status_umowy_id` int(11) NOT NULL,
`miasto_id` int(11) NOT NULL,
`klasa_lub_grupa_dziecka_id` int(11) NOT NULL,
`cennik_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
I have translate all tables and names in project to english. Also done job with command line cake bake, and all tables started to works and display fields. Problem was in models, and not declared public $displayField.
Everyboday have to do scafolding command line tool and have english names, that a lot of easy. And most importand is to declare $displayField and point it to title, or name field in each tables.
Thanks all for support.