save the record of bulk sms sent into db laravel - database

i have taken the id and mobile_num from users table.i have to insert that id name in this table as user_id,mobile_num,and status(0,1) into another table(wc_sms_status).sendSMSFunction is working fine.
public function SendBulkSms()
{
$usersNumber = User::select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
}
elseif($userNumber->mobile_num == exist && status == 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
}
else{
}
}
}

Do this :
public function SendBulkSms()
{
//assuming there is a relationship between your model users and wc_sms_status called wcSmsStatus
$usersNumber = User::with('wcSmsStatus')->select('id','mobile_num')->whereIn('id', [5,6,7,8])->get();
foreach($usersNumber as $userNumber)
{
if (!$userNumber->mobile_num)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
'user_id' => $userNumber->id,
'mobile_num' => $userNumber->mobile_num,
'status' => 1,
]);
} elseif ($userNumber->mobile_num && $userNumber['wcSmsStatus']->status === 0)
{
$this->sendSmsFunction($userNumber->mobile_num);
$this->save();
} else {
}
}
}

public function SendBulkSms()
{
$users = User::select('id','mobile_num')
->whereIn('id', [5,6,7,8])
->whereNotNull('mobile_num')
->get();
$bulkData = [];
foreach ($users as $user)
{
$this->sendSmsFunction($userNumber->mobile_num);
DB::table('wc_sms_status')->insert([
['user_id' => 'id'],
['mobile_num' => 'mobile_num'] // set the status=1 // how query can be changed?
]);
$bulkData[] = [
'user_id' => $user->id,
'mobile_num' => $user->mobile_num,
];
}
if (!empty($bulkData)) {
WcSmsStatus::insert($education); // change to your model name
unset($bulkData);
}
}
try to use in this way, it will insert bulk data, dont fergot to mention protected $fillable[] in model

Related

How to apply datatable filter when my table is passed from js?

I have js code which gets results from a query and pastes table to a div.So table is created in js and set with js.how do I apply datatables filter in such a case?
if you are using ajax request filter ,So url parameter filter may help :
for example :
This is your ajax get request url :
$.get(root_url+'index/user?id='+id+'&name='+name+'&gender='+gender, function(response){
console.log(response);
});
And this how you can caught those parameter in cakephp
public function user(){
if ($this->request->is('ajax')) {
$id = $this->request->getQuery('id');
$name = $this->request->getQuery('name');
$gender = $this->request->getQuery('gender');
$condition = [];
if ($id){
$condition = ['Users.id' => $id];
}
if (name) {
$condition = ['Users.name' => $name];
}
if (gender) {
$condition = ['Users.gender' => $gender];
}
$user = $this->Users->find()
->select([
'Users.id',
'Users.name',
'Users.gender',
'Users.create_date',])
->where(condition);
response = ['user' => $user];
return $this->response->withType('application/json')
->withStringBody(json_encode($response));
} else {
return $this->redirect(['controller' => 'pages','action' => 'error404']);
}
}

how to calculate bundle product price from array of custom selection through parameter(post data)?

the data got from post is.
[productid] => 3
[product_type] => bundle
[bundle_option] => Array
(
[1] => Array
(
[0] => 1
[1] => 2
)
[2] => Array
(
[0] => 3
[1] => 4
)
)
[qty] => 1
how to calculate the bundle price for my selections. The magento core funtions are more preferable.
Please use below code:
public function getDisplayPrice($product) {
if($product->getFinalPrice()) {
return $product->getFormatedPrice();
} else if ($product->getTypeId() == Mage_Catalog_Model_Product_Type::TYPE_BUNDLE) {
$optionCol= $product->getTypeInstance(true)
->getOptionsCollection($product);
$selectionCol= $product->getTypeInstance(true)
->getSelectionsCollection(
$product->getTypeInstance(true)->getOptionsIds($product),
$product
);
$optionCol->appendSelections($selectionCol);
$price = $product->getPrice();
foreach ($optionCol as $option) {
if($option->required) {
$selections = $option->getSelections();
$minPrice = min(array_map(function ($s) {
return $s->price;
}, $selections));
if($product->getSpecialPrice() > 0) {
$minPrice *= $product->getSpecialPrice()/100;
}
$price += round($minPrice,2);
}
}
return Mage::app()->getStore()->formatPrice($price);
} else {
return "";
}
}
I solved it by own method, not sure its acceptable or not.
$bundle_option = Mage::app ()->getRequest ()->getParam('bundle_option');
$bundle_option_array = call_user_func_array('array_merge', $bundle_option);
$price = Mage::Helper('airhotels/bundle')->getBundlePrice($productid,$bundle_option_array);
my helper file is
public function getBundlePrice($productId,$bundle_option_array) {
$product = new Mage_Catalog_Model_Product();
$product->load($productId);
$price=0;
$selectionCollection = $product->getTypeInstance(true)->getSelectionsCollection($product->getTypeInstance(true)->getOptionsIds($product), $product);
foreach($selectionCollection as $option)
{
if (in_array($option->getSelectionId(), $bundle_option_array)){
$price += $option->price;
}
}
return $price;
}

Yii2 Save multiple data in the db using foreach loop in actionCreate

In my project I want to insert multiple rows of data at a single time using the foreach loop. I have a variable which has array of elements.
For instance if my array has say 3 different elements. I want to save all these 3 elements in the 3 different db table rows. I also have other columns which are same for all the 3 array elements.
I have put them inside foreach statement but only the 1st elements gets saved. Is there any method I can achieve this?
My code
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}
Only the productline_id is different other columns will have same data for all the prdouctline_id.
Thank You!!!
You have only one model object, and you are saving only to it.
Try this:
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model = new ProductlinesStorage();
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}
maybe you can modify my code
public function actionCreate()
{
$model = new SemesterPendek();
$model->user_id = \Yii::$app->user->identity->id;
$model->npm = \Yii::$app->user->identity->username;
$modelsNilai = [new Nilai];
if ($model->load(Yii::$app->request->post())){
$model->waktu_daftar = date('Y-m-d h:m:s');
$model->save();
$modelsNilai = Tabular::createMultiple(Nilai::classname());
Tabular::loadMultiple($modelsNilai, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Tabular::validateMultiple($modelsNilai) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsNilai as $indexTools =>$modelNilai) {
$modelNilai->id_sp = $model->id;
// $modelNilai->user_id = \Yii::$app->user->identity->id;
if (! ($flag = $modelNilai->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack(); \Yii::$app->session->setFlash('error','gagal');
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsNilai' => (empty($modelsNilai)) ? [new Nilai] : $modelsNilai,
]);
}
}
You need to create a different object to save in different rows. For loop executes 3 times but every time same object is being updated. You can define new object and save each time. Below code will work
public function actionCreate($prodID)
{
$model = new ProductlinesStorage();
if ($model->load(Yii::$app->request->post())) {
$productlineID = Productlines::find()->where(['area_id' => $model->productline_id, 'product_id' => $prodID])->all();
foreach ($productlineID as $singleProductlineID) {
$model = new ProductlinesStorage();
$model->productline_id = $singleProductlineID->productline_id;
$model->user_id = Yii::$app->user->identity->user_id;
$model->isNewRecord = true;
$model->save();
}
return $this->redirect(['/product/storage?id='.$prodID]);
} else {
return $this->renderAjax('create', [
'model' => $model,
'prodID' => $prodID,
]);
}
}

Can i convert whole cakephp website to web services?

Hey I m working on project in cakephp. There will also be apps for Android as well as iPhone. How can i convert my web code to web services.
Yes, There is a way to convert complete site in web-services of any version of cakephp.
There is step to follow:
1. Put "Router::parseExtensions("pdf", "json");" this line to your routes.php in config folder before routing rules.
2. Overwrite your "beforeRender" and "Redirect" function in AppController with following:
function beforeRender() {
if (Configure::read("debug") == 0) {
if ($this->name == 'CakeError') {
$this->layout = "error";
}
} else {
if ($this->name == 'CakeError') {
$this->layout = "error";
}
}
if ($this->params["ext"] == "json") {
$paging = $requests = "";
if (isset($this->params["paging"]) && !empty($this->params["paging"])) {
$paging = $this->params["paging"];
}
$this->set(compact("paging"));
if (isset($this->request->data) && !empty($this->request->data)) {
$requests = $this->request->data;
}
$this->set(compact("requests"));
if ($this->Session->check("Message.flash") && is_array($this->Session->read("Message.flash"))) {
foreach ($this->Session->read("Message.flash") as $key => $value) {
$this->set($key, $value);
}
}
if (isset($this->{$this->modelClass}->validationErrors) && !empty($this->{$this->modelClass}->validationErrors)) {
$this->set("formError", $this->{$this->modelClass}->validationErrors);
}
if (isset($this->viewVars["params"])) {
unset($this->viewVars["params"]);
}
if (isset($this->viewVars["request"])) {
unset($this->viewVars["request"]);
}
$response = $this->viewVars;
if (!in_array($this->params["action"], $this->Auth->allowedActions) && !$this->Auth->loggedIn()) {
$response = array("authError" => true, "message" => "Please login to access.");
}
$this->set(compact("response"));
$this->set('_serialize', array("response"));
}
}
public function redirect($url, $status = NULL, $exit = true) {
if ($this->params["ext"] == "json") {
$paging = $requests = "";
if (isset($this->params["paging"]) && !empty($this->params["paging"])) {
$paging = $this->params["paging"];
}
$this->set(compact("paging"));
if (isset($this->request->data) && !empty($this->request->data)) {
$requests = $this->request->data;
}
$this->set(compact("requests"));
if (isset($this->{$this->modelClass}->validationErrors) && !empty($this->{$this->modelClass}->validationErrors)) {
$this->set("formError", $this->{$this->modelClass}->validationErrors);
}
if (!in_array($this->params["action"], $this->Auth->allowedActions) && !$this->Auth->loggedIn()) {
$response = array("authError" => true, "message" => "Please login to access.");
}
$this->set(compact("response"));
$this->set('_serialize', array("response"));
} else {
parent::redirect($url, $status = NULL, $exit = true);
}
}
Note: If you are checking for Ajax request using that request is ajax or not, and you want to response to your ajax, you have to put your response in "IF" condition
if (!isset($this->params["ext"])) {
// echo json_encode($response);
// echo "success";
// die;
}
Otherwise you can render your view in response.
I would start by reading this
You basically need to modify your routes. You also need to modify (serialize) what your controllers return.

Codeigniter - Array dont work correctly

Whenever I call this function, I get the user_id correctly but the password isnt checked...
Model:
<?php
class Prometheus_model extends CI_Model {
var $tables = array(
'bots' => 'bots',
'users' => 'users'
);
function __construct() {
parent::__construct();
}
public function tablename($table = NULL) {
if(! isset($table)) return FALSE;
return $this->tables[$table];
}
public function get($table, $where = array(), $order = NULL) {
$this->db->where($where);
if(isset($order)) {
$this->db->order_by($order);
}
$q = $this->db->get_where($this->tablename($table),$where);
$result = $q->result_array();
// You should use $q->num_rows() to detect the number of returned rows
if($q->num_rows()) {
return $result[0];
}
return $result;
}
public function update($table, $where = array(), $data) {
$this->db->update($this->tablename($table),$data,$where);
return $this->db->affected_rows();
}
public function insert($table, $data) {
$this->db->insert($this->tablename($table),$data);
return $this->db->insert_id();
}
public function delete($table, $where = array()) {
$this->db->delete($this->tablename($table),$where);
return $this->db->affected_rows();
}
public function explicit($query) {
$q = $this->db->query($query);
if(is_object($q)) {
return $q->result_array();
} else {
return $q;
}
}
public function num_rows($table, $where = NULL) {
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
public function get_bot_data_by_hw_id($bot_hw_id) {
$q = $this->get('bots', array('bot_hw_id' => $bot_hw_id));
return $q;
}
public function check_user_data($user_incredials, $user_password) {
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1){
$q = $this->get('users', array('user_name' => $this->security->xss_clean($user_incredials)));
return $q['user_id'];
}
return FALSE;
}
}
?>
My function-calling at the controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Login extends CI_Controller {
public function index(){
if($this->input->post('user_login')){
var_dump($this->prometheus_model->check_user_data($this->input->post('user_incredials'), $this->input->post('user_password')));
}
$this->load->view('login_index');
}
}
How can i fixx this ?
In your check_user_data() method you are using
if($this->num_rows('users', array('user_name' => $user_incredials, 'user_password' => $this->encrypt->decode($user_password))) == 1)
I think (logically) following code
$this->encrypt->decode($user_password)
should be
$this->encrypt->encode($user_password)
because, you are calling num_rows() method and it is
public function num_rows($table, $where = NULL)
{
if(isset($where)){
$this->db->where($where);
}
$q = $this->db->get($table);
return $q->num_rows();
}
which is actually querying the data base something like, for example,
select * from USERS where user_name = 'heera' and password = decode('abcde12345')
In this case, the password you are trying to match is need to be encrypted using encode (not decode) method, because the user has given you a non-encrypted (plain) password and the password saved in the database is already encrypted, so encode the plain password using encode method before you query the database to match with already encoded passwords.

Resources