post data based on the number of users - php

I want to ask, I want to post notification data but based on the number of existing users. I've tried like this but only post 1 data, while there are 2 user data, please help.
$acc = $registrant->update([
'approval' => 1,
'description' => $request->description,
]);
$notification = new Notification();
$roleuser = User::where('is_admin', 4)->orWhere('is_admin', '3')->get();
foreach ($roleuser as $key => $value) {
$notification->user_id = $value->id;
$notification->type = 'Menunggu Pelatihan';
$notification->title = 'Pendaftar menunggu untuk pelatihan';
$notification->message = "halo " . $value->name . " Pendaftar dengan NIP " . $registrant->nip . " menunggu untuk pelatihan";
$notification->save();
}

Related

Bronto PHP API to get subscription status to a specific list for a specific email

I am trying to figure out how to using PHP and the Bronto API to identify if a user is subscribed or unsubscribed to a specific email list.
I am using the below code and my issue is that regardless if the user is subscribed or unsubscribed I always get a status of "active" for the user and what I need to see is not if they are on the list but unsubscribed or on the list and subscribed.
Anyway know what I should change?
<?php
$client = new SoapClient('https://api.bronto.com/v4?wsdl', array('trace' => 1,
'features' => SOAP_SINGLE_ELEMENT_ARRAYS));
try {
//token
$token = "abc 123 and yz";
//print "logging in\n";
$sessionId = $client->login(array('apiToken' => $token))->return;
$session_header = new SoapHeader("http://api.bronto.com/v4",
'sessionHeader',
array('sessionId' => $sessionId));
$client->__setSoapHeaders(array($session_header));
// set up a filter to read contacts and match on email address
$filter = array('email' => array(array('operator' => 'EqualTo',
'value' => 'fake.person#gmail.com'
),
),
);
$contacts = $client->readContacts(array('pageNumber' => 1,
'includeLists' => false,
'filter' => $filter,
)
)->return;
// print matching contact email addresses
foreach ($contacts as $contact) {
//$contact->status always seems to have a status of active or null ??
if($contact->status ='subscribed')
{
echo " <a href='' class='btn btn-primary'>Unsubscribe</a>";
}
else if($contact->status ='Unsubscribed')
{
echo " <a href=''>Subscribe</a>";
}
//print $contact->email . ': ' . $contact->status . "\n";
}
} catch (Exception $e) {
print "uncaught exception\n";
print_r($e);
}
I think you are misusing the object property "status". If you look at this page, https://help.bronto.com/bmp/reference/r_api_soap_contactfilter.html, it shows all the the things status equals to.
To be honest I think it would be better to use this the filter function to select the unsubscribed users and perform logic based on results of the filter.What does $contact->status == "unsub" return?
I mean there is always this https://help.bronto.com/bmp/reference/r_api_soap_readunsubscribes.html method for selecting unsubscribed users and then perform logic on users not found in this group.
// print matching contact email addresses
foreach ($contacts as $contact) {
//$contact->status always seems to have a status of active or null ??
if($contact->status != 'unsub')
{
echo " <a href='' class='btn btn-primary'>Unsubscribe</a>";
}
else if($contact->status =='unsub')
{
echo " <a href=''>Subscribe</a>";
}
//print $contact->email . ': ' . $contact->status . "\n";
}
I just noticed that your operators are not right. you have "=", shouldn't it be "=="?

Add fields in laravel dynamically and unlimited

I have part of my website where users or admins can add restaurant list (is really like posts, just different naming)
There is some fixed inputs such as (title, description and map) I also need a part where users/admins can add restaurants menu this options is obviously can be different for each restaurant as their menu is a short list or long list.
So what I need is like + button where people can add fields and named their menu items with another field for the price of each item.
So my question is how to achieve this option?
What do I have at the moment?
Restaurant migrate:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateRestaurantsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('restaurants', function (Blueprint $table) {
$table->increments('id');
$table->string('title')->unique();
$table->string('slug')->unique();
$table->string('description')->nullable();
$table->string('image')->nullable();
$table->string('menu')->nullable();
$table->string('address')->nullable();
$table->integer('worktimes_id')->unsigned();
$table->integer('workday_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->string('verified')->default(0);
$table->string('status')->default(0);
$table->timestamps();
});
Schema::table('restaurants', function($table) {
$table->foreign('worktimes_id')->references('id')->on('worktimes');
$table->foreign('workday_id')->references('id')->on('workdays');
$table->foreign('user_id')->references('id')->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('restaurants');
}
}
That's all, I still didn't create CRUD controller for restaurant because I'm holding for this option and your opinions.
Thanks.
UPDATE
STORE METHOD:
public function store(Request $request)
{
//Validating title and body field
$this->validate($request, array(
'title'=>'required|max:225',
'slug' =>'required|max:255',
'image' =>'sometimes|image',
'description' => 'required|max:100000',
'address' => 'sometimes|max:500',
'user_id' => 'required|numeric',
'verified' => 'sometimes',
'status' => 'required|numeric',
));
$restaurant = new Restaurant;
$restaurant->title = $request->input('title');
$restaurant->slug = $request->input('slug');
$restaurant->description = $request->input('description');
$restaurant->address = $request->input('address');
$restaurant->user_id = $request->input('user_id');
$restaurant->verified = $request->input('verified');
$restaurant->status = $request->input('status');
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'restaurant' . '-' . time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/');
$request->file('image')->move($location, $filename);
$restaurant->image = $filename;
}
// menu
$newArray = array();
$menuArray = $request->custom_menu; //Contains an array of Menu Values
$priceArray = $request->custom_price; //Contains an array of Price Values
//Creating new array with ARRAY KEY : MENU VALUES and ARRAY VALUE: PRICE VALUES
foreach ($menuArray as $key => $singleMenu) {
$newArray[$singleMenu] = $priceArray[$key];
}
//Output : array("Menu01" => "Price01", "Menu02" => "Price 02", "Menu03" => "Price 04", "Menu04" => "Price 05")
//Converting array to json format to store in your table row 'custom_menu_price'
$jsonFormatData = json_encode($newArray);
//Output like: {"Menu01":"Price01","Menu02":"Price 02","Menu03":"Price 04","Menu04":"Price 05"}
// Save in DB
//
//
//
// To retrieve back from DB to MENU and PRICE values as ARRAY
$CustomArray = json_decode($jsonFormatData, TRUE);
foreach ($CustomArray as $menu => $price) {
echo "Menu:".$menu."<br>";
echo "Price:".$price."<br>";
}
// menu
$restaurant->save();
$restaurant->workdays()->sync($request->workdays, false);
$restaurant->worktimes()->sync($request->worktimes, false);
//Display a successful message upon save
Session::flash('flash_message', 'Restaurant, '. $restaurant->title.' created');
return redirect()->route('restaurants.index');
What you can do is
1) add another one table row for custom_menu_price in your migration file
$table->string('custom_menu_price')->nullable();
2) Modify your form
<form method="POST" action="{{ ...... }}">
{{ csrf_field() }}
//I'm Looping the input fields 5 times here
#for($i=0; $i<5; $i++)
Enter Menu {{ $i }} : <input type="text" name="custom_menu[]"> //**Assign name as ARRAY
Enter Price {{ $i }} : <input type="text" name="custom_price[]"> //**Assign name as ARRAY
<br><br>
#endfor
<input type="submit" name="submit">
</form>
3) In your controller
public function store(Request $request) {
//Validating title and body field
$this->validate($request, array(
'title'=>'required|max:225',
'slug' =>'required|max:255',
'image' =>'sometimes|image',
'description' => 'required|max:100000',
'address' => 'sometimes|max:500',
'user_id' => 'required|numeric',
'verified' => 'sometimes',
'status' => 'required|numeric',
));
$restaurant = new Restaurant;
$restaurant->title = $request->input('title');
$restaurant->slug = $request->input('slug');
$restaurant->description = $request->input('description');
$restaurant->address = $request->input('address');
$restaurant->user_id = $request->input('user_id');
$restaurant->verified = $request->input('verified');
$restaurant->status = $request->input('status');
if ($request->hasFile('image')) {
$image = $request->file('image');
$filename = 'restaurant' . '-' . time() . '.' . $image->getClientOriginalExtension();
$location = public_path('images/');
$request->file('image')->move($location, $filename);
$restaurant->image = $filename;
}
// menu
$newArray = array();
$menuArray = $request->custom_menu; //Contains an array of Menu Values
$priceArray = $request->custom_price; //Contains an array of Price Values
//Creating new array with ARRAY KEY : MENU VALUES and ARRAY VALUE: PRICE VALUES
foreach ($menuArray as $key => $singleMenu) {
$newArray[$singleMenu] = $priceArray[$key];
}
//Output : array("Menu01" => "Price01", "Menu02" => "Price 02", "Menu03" => "Price 04", "Menu04" => "Price 05")
//Converting array to json format to store in your table row 'custom_menu_price'
$jsonFormatData = json_encode($newArray);
//Output like: {"Menu01":"Price01","Menu02":"Price 02","Menu03":"Price 04","Menu04":"Price 05"}
// Save in DB
$restaurant->custom_menu_price = $jsonFormatData;
// menu
$restaurant->save();
$restaurant->workdays()->sync($request->workdays, false);
$restaurant->worktimes()->sync($request->worktimes, false);
//Display a successful message upon save
Session::flash('flash_message', 'Restaurant, '. $restaurant->title.' created');
return redirect()->route('restaurants.index');
}
inside your front.restaurantshow view:
#php
// To retrieve back from DB to MENU and PRICE values as ARRAY
$CustomArray = json_decode($restaurant->custom_menu_price, TRUE);
#endphp
#foreach ($CustomArray as $menu => $price)
Menu Name: {{ $menu }} <br>
Menu Price: {{ $price }} <br><br>
#endforeach
Hope it makes sense.

how can i get the Quantity by considering two conditions in table customer_stock

I am stuck with a problem in php, mysql and json
I am not able to retrieve data from the database by selecting two conditions
I have attached a screenshot as well
I want to retrieve the quantity from table customer_stock by considering two conditions: customer and name
$line = $db->queryUniqueObject("SELECT * FROM stock_details WHERE stock_name ='" . $_POST['stock_name1'] . "'");
$cost = $line->company_price;
$sell = $line->selling_price;
$stock_id = $line->stock_id;
$line = $db->queryUniqueObject("SELECT * FROM customer_stock WHERE name='" . $_POST['stock_name1'] . "'");
$stock = $line->quantity;
if ($line != NULL) {
$arr = array("cost" => "$cost", "sell" => "$sell", "stock" => "$stock", "guid" => $stock_id);
echo json_encode($arr);
} else {
$arr1 = array("no" => "no");
echo json_encode($arr1);
}

How to insert to the mysql array object

I'm new to Rest api,I'm developing a student management system using rest api and angular js.When I registering students from student registration form there is a ng-grid to select courses of students going attend in the institute,
I loaded selected courses in an angular object like this.
var Course = {
"std_id": "1",
"course_id": $scope.studentCourse,
"started_date": $scope.startedDate
};
in this courses object courses are selected values from ng-grid plus student and registrations date.My problem is I have loaded objects to an object and Im stuck with process this obejects in side my restfull api.
my json object pass like this
[{
"std_id":"1",
"courses":
[{"course_id":"2"},
{"course_id":"4"},
{"course_id":"8"}],
"started_date":"2015-9-18"
}]
Here my php rest call
private function InsertStudentCourse() {
if ($this->get_request_method() != "POST") {
$this->response('', 406);
}
$course= json_decode(file_get_contents("php://input"), true);
$column_names = array ('std_id','course_id','started_date');
$columns = '';
$values = '';
$keys = array_keys($course);
//$this->response($this->json($deviceTypeId), 200);
foreach ($column_names as $desired_key) { // Check the Department received. If blank insert blank into the array.
if (!in_array($desired_key, $keys)) {
$$desired_key = '';
} else {
$$desired_key = $course[$desired_key];
}
$columns = $columns . $desired_key . ',';
$values = $values . "'" . $$desired_key . "',";
}
$query = "INSERT INTO student_course (" . trim($columns, ',') . ") VALUES(" . trim($values, ',') . ")";
//$query = "INSERT INTO student_course ('course_id') VALUES ($c)";
if (!empty($course)) {
$r = $this->mysqli->query($query) or die($this->mysqli->error . __LINE__);
$success = array('status' => "Success", "msg" => "student Course Type Created Successfully.", "data" => $course);
$this->response($this->json($success), 200);
} else {
$this->response('', 204);
} //"No Content" status
}
I want to insert this object array like this
std_id course_id started_date
- 1 , 2, 2015-9-18
- 1 , 4, 2015-9-18
- 1 , 8, 2015-9-18
how can I get this done

extracting database rows from an array within a foreach loop

I am trying to extract 4 rows of product prices from a database table.
AU$ 11.00
AU$ 19.00
AU$ 32.00
AU$ 52.00
When i execute the code below i only retrieve the last value AU$ 52.00 from the database.
Array ( [CURRENCY] => AU$ 52.00 )
This is my code
$sql = DB::getInstance()->query('SELECT monthly FROM products');
foreach($sql->results() as $row) {
$price = '<small>AU$</small> ' . number_format($row->monthly, 2) . '<br>';
}
$currency = array(
'CURRENCY' => $price,
);
print_r($currency['CURRENCY']);
die();
?>
Probably overlooking somthing simple but my head is all bitter and twisted now. Any help will be useful. Thanks in advance
EDIT TO QUESTION
This will be a currency converter so the code below may help with how it will work
$currencies = array('AUD', 'USD', 'GBP', 'EUR', 'THB');
$get_cur = Input::get('currency');
if(isset($get_cur) === true && in_array($get_cur, $currencies) === true) {
$_SESSION['currency'] = $get_cur;
} else if (isset($_SESSION['currency']) === false) {
$_SESSION['currency'] = 'AUD';
}
include 'currency/' . $_SESSION['currency'] . '.php';
From each linked currency will go to AUD, USD, GBP etc etc
<a href="?currency=AUD">
Linked to AUD.php which is the code from the original question. This is why i need to link
$currency['CURRENCY']
This will be the defined name in the array of each currency.
Hope this helps
EDIT TO QUESTION #2
<?php
// Currency Covert Class
class CurrencyConverter {
public function convert($amount, $from, $to) {
$data = file_get_contents('https://www.google.com/finance/converter?a=' . $amount . '&from=' . $from . '&to=' . $to);
preg_match("/<span class=bld>(.*)<\/span>/", $data, $converted);
$converted = preg_replace("/[^0-9.]/", "", $converted[1]);
return $converted;
}
}
////////////////////////
$currencies = array('AUD', 'USD', 'GBP', 'EUR', 'THB');
$get_lang = Input::get('currency');
if(isset($get_lang) === true && in_array($get_lang, $currencies) === true) {
$_SESSION['currency'] = $get_lang; //Get's the currency from whichever currency is selected from the $currencies = array('AUD', 'USD', 'GBP', 'EUR', 'THB');
} else if (isset($_SESSION['currency']) === false) {
$_SESSION['currency'] = 'AUD'; //If no currency selected, then default is AUD
}
include 'currency/' . $_SESSION['currency'] . '.php'; //Selects the currenct .php file eg; 'AUD', 'USD', 'GBP', 'EUR', 'THB'
//If AUD.php then it $_GET currency eg; ?currency=AUD, ?currency=USD, ?currency=GBP
// This is AUD.php (DEFAULT CURRENCY)
$sql = DB::getInstance()->query('SELECT monthly FROM products');
foreach($sql->results() as $row) {
$currency = array(
'CURRENCY' => '<small>AU$</small> ' . number_format($row->monthly, 2),
);
}
// This is USD.php
$converter = new CurrencyConverter;
$sql = DB::getInstance()->query('SELECT monthly FROM products');
foreach($sql->results() as $row) {
$currency = array(
'CURRENCY' => '<small>US$</small> ' . number_format($converter->convert($row->monthly, 'AUD', 'USD'), 2),
);
}
//So you can see that all the currency .php files have the key array word of 'CURRENCY', and this is how it will work from the $_SESSION['currency'] to the $currency['CURRENCY'] array
//Then simply echo out $currency['CURRENCY'] and it will convert to each $currencies = array('AUD', 'USD', 'GBP', 'EUR', 'THB');
echo '<p>' . $currency['CURRENCY'] . '<span>' . $lang['PER_MONTH'] . '</span></p>';
?>
EDIT TO QUESTION #3
I think i have found the issue, overlooked by me. It is inside a nested foreach loop
$sql = DB::getInstance()->query('SELECT * FROM products ORDER BY id ASC');
foreach($sql->results() as $row) {
if(escape($row->popular)) {
echo '<div class="col-md-3 price-table ' . escape($row->popular) . '">';
} else {
echo '<div class="col-md-3 price-table">';
}
?>
<h3><strong><?php echo escape($row->name) ?></strong><br><?php echo $lang['PACKAGE'] ?></h3>
<?php
///HERE IS WHERE IT GETS PULLED IN FROM AUD.php, USD.php, GBP.php, etc etc///
///START OF AUD.php///
$sql = DB::getInstance()->query('SELECT monthly FROM products');
$currency = array();
$currency['CURRENCY'] = array();
foreach($sql->results() as $row) {
array_push($currency['CURRENCY'], '<small>AU$</small> ' . number_format($row->monthly, 2));
}
///END OF AUD.php///
echo '<p>' . implode($currency['CURRENCY'], ' <span>' . $lang['PER_MONTH'] . '</span>') . '</p>';
The arrays is below
Array
(
[0] => AU$ 11.00
[1] => AU$ 19.00
[2] => AU$ 32.00
[3] => AU$ 52.00
)
I need it like this to be able to convert the currencies. So i need this;
echo '<p>' . implode($currency['CURRENCY'], ' <span>' . $lang['PER_MONTH'] . '</span>') . '</p>';
To echo out below in the first pass of the loop
echo '<p> AU$ 11.00 <span>Per Month</span></p>';
And echo out below in the second pass of the loop
echo '<p> AU$ 19.00 <span>Per Month</span></p>';
And so on. At the moment i am getting all four values on every pass of the loop
You arent adding the value in your loop so you only get the last value in $price
foreach($sql->results() as $row) {
$price = '<small>AU$</small> ' . number_format($row->monthly, 2) . '<br>';
$currency[]=array('CURRENCY' => $price);
}
Do this. it will do it perfectly
$sql = DB::getInstance()->query('SELECT monthly FROM products');
$currency = array();
$i=0;
foreach($sql->results() as $row) {
$price = '<small>AU$</small> ' . number_format($row->monthly, 2) . '<br>';
$currency['CURRENCY'][$i] = $price;
$i++;
}
print_r($currency['CURRENCY']);
?>
Do this:
$currency = array();
$currency['currency'] = array()
foreach($sql->results() as $row) {
array_push($currency['currency'], '<small>AU$</small> ' . number_format($row->monthly, 2));
}
echo '<p>' . implode($currency['CURRENCY'], ' <span>' . $lang['PER_MONTH'] . '</span><br />') . </p>';
Now foreach will push a value into the array $currency, with the correct currency.
Close foreach loop after you have assigned price to currency.
$currency = array();
foreach($sql->results() as $row) {
$price = '<small>AU$</small> ' . number_format($row->monthly, 2) . '<br>';
$currency[] = $price;
}

Categories