How to calculate with html form select and option in php - php

A form that takes a lot of information from the user and processes it, and finally a number is displayed.
A number of objects are obtained according to other objects.
index.php
<form action="calc.php" method="POST">
<select name="NumberOfPeople2">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="NumberOfBathTimes">
<option value="1">one</option>
<option value="2">two</option>
</select>
<select name="DurationOfBathing">
<option value="10">10 min</option>
<option value="20">20 min</option>
</select>
<input type="submit" value="submit">
</form>
calc.php
<?php
include 'include/calc.inc.php';
$NumberOfPeople = $_POST['NumberOfPeople'];
$NumberOfBathTimes = $_POST['NumberOfBathTimes'];
if($_POST['DurationOfBathing']=='10')
{
$DurationOfBathing='60';
}
if($_POST['DurationOfBathing']=='20')
{
$DurationOfBathing='100';
}
if($_POST['NumberOfBathTimes']=='1')
{
$FactorUseBath='0.14285714';
$FactorNumberBath='1.2';
}
if($_POST['NumberOfBathTimes']=='2')
{
$FactorUseBath='0.28571429';
$FactorNumberBath='1.2';
}
$ConsumptionBath = new Calc($NumberOfPeople,$DurationOfBathing,$FactorUseBath,$FactorNumberBath);
echo $ConsumptionBath->calcMethod();
calc.inc.php
<?php
class Calc{
public $NumberOfPeople;
public $DurationOfBathing;
public $FactorUseBath;
public $FactorNumberBath;
public function __construct($NumberOfPeople,$DurationOfBathing,$FactorUseBath,$FactorNumberBath){
$this->NumberOfPeople = $NumberOfPeople;
$this->DurationOfBathing; = $DurationOfBathing;
$this->FactorUseBath; = $FactorUseBath;
$this->FactorNumberBath; = $FactorNumberBath;
}
public function calcMethod(){
$result = $this->DurationOfBathing*$this->FactorUseBath;*$this->FactorNumberBath*$this->NumberOfPeople;
return $result;
}
}
All objects obtained must be multiplied.
The answer is $ConsumptionBath
Is this the right way?

This is right way, but you should declare each and every variable somewhere which is used in script. For example, in your given script, variable $DurationOfBathing is initialised only in if conditions and will give undefined variable error in case if conditions fails. So I've updated code below:
include 'include/calc.inc.php';
$NumberOfPeople = $_POST['NumberOfPeople'];
$NumberOfBathTimes = $_POST['NumberOfBathTimes'];
$DurationOfBathing = $FactorUseBath = $FactorNumberBath = '';
if ($_POST['DurationOfBathing'] == '10') {
$DurationOfBathing = '60';
} else if ($_POST['DurationOfBathing'] == '20') {
$DurationOfBathing = '100';
}
if ($_POST['NumberOfBathTimes'] == '1') {
$FactorUseBath = '0.14285714';
$FactorNumberBath = '1.2';
} else if ($_POST['NumberOfBathTimes'] == '2') {
$FactorUseBath = '0.28571429';
$FactorNumberBath = '1.2';
}
$ConsumptionBath = new Calc($NumberOfPeople, $DurationOfBathing, $FactorUseBath, $FactorNumberBath);
echo $ConsumptionBath->calcMethod();
Update
There is some problem in class as well. Some extra semi colons ; are added there. Use this updated code:
<?php
class Calc {
public $NumberOfPeople;
public $DurationOfBathing;
public $FactorUseBath;
public $FactorNumberBath;
public function __construct($NumberOfPeople, $DurationOfBathing, $FactorUseBath, $FactorNumberBath) {
$this->NumberOfPeople = $NumberOfPeople;
$this->DurationOfBathing = $DurationOfBathing;
$this->FactorUseBath = $FactorUseBath;
$this->FactorNumberBath = $FactorNumberBath;
}
public function calcMethod() {
$result = $this->DurationOfBathing * $this->FactorUseBath * $this->FactorNumberBath * $this->NumberOfPeople;
return $result;
}
}

Related

Laravel Product Filter by Price

I have a filter route to filter my products by brand & weight & count and taste and all are working fine but when i want to add a sort filter its not working, i want to sort it by pirce ( Ascending and descending).
here is my codes
Route:
Route::match(['get', 'post'], 'products/filter', [SearchController::class, 'filterall']);
SearchController:
public function filterall(Request $request){
$data = $request->all();
// echo "<pre>"; print_r($data);
$brandUrl = "";
$weightUrl = "";
$countUrl = "";
$tasteUrl = "";
$sortUrl = "";
if(!empty($data['brandFilter'])){
foreach ($data['brandFilter'] as $brand){
if(empty($brandUrl)){
$brandUrl = "&brand=".$brand;
}else{
$brandUrl .= "-".$brand;
}
}
}
if(!empty($data['weightFilter'])){
foreach ($data['weightFilter'] as $weight){
if(empty($weightUrl)){
$weightUrl = "&weight=".$weight;
}else{
$weightUrl .= "-".$weight;
}
}
}
if(!empty($data['countFilter'])){
foreach ($data['countFilter'] as $count){
if(empty($countUrl)){
$countUrl = "&count=".$count;
}else{
$countUrl .= "-".$count;
}
}
}
if(!empty($data['tasteFilter'])){
foreach ($data['tasteFilter'] as $taste){
if(empty($tasteUrl)){
$tasteUrl = "&taste=".$taste;
}else{
$tasteUrl .= "-".$taste;
}
}
}
if(!empty($data['sort'])){
foreach ($data['sort'] as $sort){
if(empty($sortUrl)){
$sortUrl = "&sort=".$sort;
}else{
$sortUrl .= "-".$sort;
}
}
}
$finalUrl = "category/".$data['url_id'].'/'.$data['url_slug']."?".$brandUrl.$weightUrl.$countUrl.$tasteUrl.$sortUrl;
return redirect::to($finalUrl);
}
*** My View Controller ***
public function allCategory(Request $request, $id){
$catt = DB::table('categories')->where('id', $id)->first();
$products = Product::where('category_id', $catt->id)->where('status', '1')
->orderBy('brand_id', 'ASC');
if(!empty($_GET['brand'])){
$brandArray = explode('-', $_GET['brand']);
$products = $products->whereIn('brand_id', $brandArray);
}
if(!empty($_GET['weight'])){
$weightArray = explode('-', $_GET['weight']);
$products = $products->whereIn('product_weight', $weightArray);
}
if(!empty($_GET['count'])){
$countArray = explode('-', $_GET['count']);
$products = $products->whereIn('product_count', $countArray);
}
if(!empty($_GET['taste'])){
$tasteArray = explode(',', $_GET['taste']);
foreach ($tasteArray as $taste){
$products = $products->where('product_taste','LIKE', "%$taste%");
}
if(!empty($_GET['sort'])){
$sortArray = explode('-', $_GET['sort']);
$products = $products->orderBy('selling_price', $sortArray);
}
}
$products = $products->paginate(12);
return view('pages.all_category', compact('products', 'catt'));
}
and this is the view code:
<div class="row" id="search-results">
<div class="col-lg-12 col-md-12">
<div class="toolbar toolbar-products">
<div class="toolbar-sorter sorter">
<label class="sorter-label" for="sort">Sort By</label>
#if(!empty($_GET['sort']))
<?php $sortArray = explode('-', $_GET['sort']) ?>
#endif
<select id="sort" name="sort[]" class="sorter-options" onchange="javascript:this.form.submit();">
<option value="">Select</option>
#if(!empty($_GET['sort']))
<?php $price = $_GET['sort'] ?>
#endif
<option value="ASC" #if(!empty($sortArray) && in_array('ASC', $sortArray)) selected="" #endif>Lowest Price</option>
<option value="DESC" #if(!empty($sortArray) && in_array('DESC', $sortArray)) selected="" #endif>Highest Price</option>
</select>
</div>
</div>
</div>
</div>
im doing this by Form in page.
I think orderBy in front Controller is not working is there other way to sort that?

Get values ​from select2 with php without jquery

I have a registration system where there are several fields. One of the registration fields is Segments and they come from the database:
public function comboSegmentos($key)
{
$sqlMostrar = mysqli_query($this->conexao, "SELECT * FROM loja_segmentos;");
if (mysqli_num_rows($sqlMostrar) == 0)
{
$mostrar = "<div style='color: red'>Nenhuma segmento cadastrado até o momento.</div>";
}
else
{
$mostrar = "<select name='Segments[]' id='segmentos' class='form-control select2' multiple='multiple' style='width: 35%'>";
while ($jmMostrar = mysqli_fetch_object($sqlMostrar))
{
$mostrar .= "<option value='".$jmMostrar->Segmentos."' ".$selected.">".$jmMostrar->Segmentos."</option>";
}
$mostrar .= "</select>";
}
return $mostrar;
}
So that the method doesn't have too many parameters, I did it like this:
<?php
...
$dados = array_filter($_POST);
echo $metodos->cadastrarProdutos($dados);
Method cadastrarProdutos($dados)
But I'm not able to get the values ​​of the Segments even using foreach().
<?php
public function cadastrarProdutos(array $dados)
{
...
$segments = $dados["Segments"];
foreach($segments as $seg)
{
$segm = $seg;
}
...
}
How can I get the values ​​of the select2 field and get them using a PHP method without Jquery?
I managed to solve it as follows:
<?php
public function cadastrarProdutos(array $dados)
{
...
$segments = $dados["Segments"];
$segm = array();
foreach($segments as $seg)
{
$segm[] = $seg;
}
$segments = implode(',',$segm);
...
}

Syntax error in other file when adding a foreach

Here's the error i'm getting :
syntax error, unexpected end of file, expecting function (T_FUNCTION)' in D:\User\Documents...\Controllers\DeviceController.php:68
It happens in this code :
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Data\Campaign;
use App\Data\Device;
use App\Helpers\Database;
use App\Helpers\DateHelpers;
use App\Helpers\ProfileHelpers;
use App\Helpers\Utils;
use Illuminate\Http\Request;
class DeviceController extends ApiController
{
public function show($deviceId)
{
return Device::find($deviceId);
}
public function update(Request $request, $deviceId)
{
$isAlertActive = filter_var($request->input('isAlertActive'), FILTER_VALIDATE_BOOLEAN);
$isAlertAfter5Pushes = filter_var($request->input('isAlertAfter5Pushes'), FILTER_VALIDATE_BOOLEAN);
$isAlertAfter10Pushes = filter_var($request->input('isAlertAfter10Pushes'), FILTER_VALIDATE_BOOLEAN);
$hasAtLeastOneSettingActive = $isAlertActive || $isAlertAfter5Pushes || $isAlertAfter10Pushes;
$settings = [
'is_alert' => $isAlertActive,
'is_alert_after_5_pushes' => $isAlertAfter5Pushes,
'is_alert_after_10_pushes' => $isAlertAfter10Pushes
];
if ($isAlertActive) {
$settings['alert_seuil'] = intval($request->input('alertThreshold'));
$settings['alert_votemini'] = intval($request->input('minVoteCountBeforeAlert'));
}
if ($hasAtLeastOneSettingActive)
$settings['next_alert_in_hours'] = intval($request->input('nextAlertInHours'));
Device::where('id_device', $deviceId)
->update($settings);
}
/////////////////////////////////////////////////////////////////////////////
public function putInLocation($sectionId, $locationName)
{
$section = Section::find($sectionId);
if ($section && $section->area->id_client == $this->clientId) {
Location::createLocation($sectionId, $locationName);
return self::jsonSuccess();
}
else
return self::jsonBadRequest();
}
public function delete($locationId)
{
$location = Location::find($locationId);
if ($location && $location->section->area->id_client == $this->clientId) {
$location->delete();
return self::jsonSuccess();
}
else
return self::jsonBadRequest();
}
}
?>
I don't see any syntax error there, i checked the brackets multiple times but maybe i missed something ?
What's weird for me is that there is no syntax error until i add a foreach in another file (D:\User\Documents...\Views\Partials\areasettings.php). Here's the foreach :
<div class="col-lg-3 col-lg-offset-0 v">
<div class="input-group">
<span class="input-group-addon"><span class="glyphicon glyphicon-barcode"></span></span>
<select class="form-control" id="deviceSelect">
<option selected disabled> <?php echo trans('areasettings.add_id_placeholder') ?> </option>
<option> TEST </option>
<?php
$devices = $db->fetchAll("select `id_device_mac` from `dashboard_demo.nao_device`");
foreach ($devices as $device) {
$idDevice = $device->id_device;
$idDeviceMac = $device->id_device_mac;
//echo "<option value=\"$idDevice\">$idDeviceMac</option>\n";
<option value="<?= $device['id_device_mac'] ?>"><?= $device['id_device_mac'] ?></option>
}
?>
</select>
<!--<input type="text" class="form-control" placeholder="<?php echo trans('areasettings.add_id_placeholder') ?>" autocomplete="off"
ng-model="newSectionName">-->
</div>
</div>
Thanks in advance for helping me !
EDIT : Changed the fetchAll with this line (laravel way) :
$devices = DB::table('dashboard_demo.nao_device')->select('id_device_mac')->get()
But i still get the same error.
I searched deeper in my logs and also found that devices is undefined apparently.
This line looks wrong, if you are using vanilla PDO.
$devices = $db->fetchAll("select `id_device_mac` from `dashboard_demo.nao_device`");
PDO::fetchAll does not execute a query, it just processes the resultset of an already executed query.
So something like this perhaps
$sql = 'select `id_device_mac` from `dashboard_demo.nao_device`';
$result = $db->query($sql);
if ( ! $result ) {
print_r($db->errorInfo())
exit;
}
while ($device = $result->fetch(PDO::FETCH_OBJ)) {
$idDevice = $device->id_device;
$idDeviceMac = $device->id_device_mac;
echo "<option value='$idDevice'>$idDeviceMac</option>\n";
}
This way should show you if any errors happened in the query.
Also changed the content of the while loop. You were using an array notation in there but an objct notation when getting data from the $device variable above?

Pagination with search/filter using form

I am new to codeigniter framework and I'm trying to do pagination with a search filter.
I've come across answers such as this (which has no answer though) and this which also has no ticked answer so I'm not sure if it's the correct way to follow, moreover confused.
What I have is by default the page would show all result of a table using pagination.
Now I'm stuck and gotten into quite a mess so do pardon me if there are a few obvious mistakes.
So what I'm trying to do here is when the user selects a value in the drop down box and submits let's say Customer A, I'm expecting rows containing Customer A from columncustomer only.
However after submitting I'm getting all the results and worse, in plain text without my header and footer (separate views). I understand that's because I didn't call them but still it doesn't display those with Customer A only.
Been trying to find a simple solution where after a form submit, paginate query would execute according to the value gotten from the form, and display the selected rows. Can't seem to find any other than the two links, so I'm not sure if I'm filtering the right way.
View
<form method="POST" action='<?php echo base_url("index.php/Home/load_lot_table")?>' class="form-inline">
<select id="cust_drop_down" name="cust_drop_down" class="form-control input-mini">
<option value="all">All</option>
<option value="custA">Customer A</option>
<option value="custB">Customer B</option>
</select>
<input type="submit" class="btn btn-primary purple_button" value="Search">
</form>
Controller
public function on_hold_lot() // Default function to display result
{
$data['title'] = 'Search System';
$this->load->view('templates/normal_header', $data);
$this->populate_customer_dropdown(); // private
$this->load_lot_table(); // public
$this->load->view('templates/legend_footer', $data);
}
public function load_lot_table() // Main pagination function
{
if(isset($this->input->post))
{
$search = array(
'customer' => $this->input->post('cust_drop_down')
);
}
else
{
$search = array(
'customer' => 'all',
'stage' => 'all',
'lot_status' => 'all'
);
}
$config = array();
$config['base_url'] = base_url()."index.php/Home/on_hold_lot";
$config['total_rows'] = $this->home_model->record_count();
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['next_link'] = 'Next';
$config['prev_link'] = 'Previous';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$results = $this->home_model->fetch_lots($config['per_page'], $page, $search);
$data['disp_rows'] = $results;
$data['links'] = $this->pagination->create_links();
return $this->load->view('home/lot_disposition', $data);
}
Model
public function record_count()
{
return $this->db->count_all('disp_dummy');
}
public function fetch_lots($limit, $start, $search = null)
{
$this->db->limit($limit, $start);
if($search != null && $search['customer'] != 'all')
{
$this->db->where('customer', $search['customer']);
}
$query = $this->db->get('disp_dummy');
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
$data[] = $row;
}
return $data;
}
else
{
return false;
}
}
You will need to make some changes to your code :
First of all use GET request to submit your search as the you wont get the posted parameters in second page for pagination :
VIEW :
<form method="GET" action='<?php echo base_url("index.php/Home/load_lot_table")?>' class="form-inline">
<select id="cust_drop_down" name="cust_drop_down" class="form-control input-mini">
<option value="all">All</option>
<option value="custA">Customer A</option>
<option value="custB">Customer B</option>
</select>
<input type="submit" class="btn btn-primary purple_button" value="Search">
</form>
In your controller You will have to check the get value and not the post values. Also in the $config['total_rows'] you need to pass the total number of rows that are present in your current query and not in the table. So it would be something like this :
CONTROLLER :
public function load_lot_table() // Main pagination function
{
if($this->input->get('cust_drop_down'))
{
$search = array(
'customer' => $this->input->get('cust_drop_down')
);
}
else
{
$search = array(
'customer' => 'all',
'stage' => 'all',
'lot_status' => 'all'
);
}
$config = array();
$config['base_url'] = base_url()."index.php/Home/on_hold_lot";
$config['total_rows'] = $this->home_model->fetch_lots($search)->num_rows();
$config['per_page'] = 10;
$config['uri_segment'] = 3;
$config['next_link'] = 'Next';
$config['prev_link'] = 'Previous';
$this->pagination->initialize($config);
$page = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
$results = $this->home_model->fetch_lots($search, $config['per_page'], $page)->result_array();
$data['disp_rows'] = $results;
$data['links'] = $this->pagination->create_links();
return $this->load->view('home/lot_disposition', $data);
}
In your Model make modificaiton in the search function as below :
Model
public function fetch_lots($search = null, $limit = null, $start = 0)
{
if($limit != null){
$this->db->limit($limit, $start);
}
if($search != null && $search['customer'] != 'all')
{
$this->db->where('customer', $search['customer']);
}
$query = $this->db->get('disp_dummy');
if($query->num_rows() > 0)
{
return $query;
}
else
{
return false;
}
}

Php echo variables from a function outside the function when calling it

I have this php function which looks up rows from a database table
if (!function_exists("ContactLookup")) {
function ContactLookup($column, $clause, $value, $limit1=0, $limit2=1)
{
global $conn;
$ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
$ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
while ($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs)) {
$foremame =$ContactLookup_Result["forename"];
$surname = $ContactLookup_Result["surname"];
}
}
}
This just echoes the results but if I wanted to put the results into a select element how would I do this
Within the while loop would I create the variables then echo the variables when I call the function? Or is there another way around this?
Like:
<?php ContactLookup("company_sequence", "=", $result["contact"],"0","10"); ?>
><select name="contactsequence" id="contactsequence">
<option value=""><?php echo $forename; ?></option>
</select
Make your function return an array
function ContactLookup ($column, $clause, $value, $limit1=0, $limit2=1) {
global $conn;
$ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
$ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
$results = [];
while($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs))
{
$results[] = [
'forename'=> $ContactLookup_Result["forename"],
'surname'=> $ContactLookup_Result["surname"]
];
}
return $results;
}
Then you can loop through it:
<?php
$names = ContactLookup("company_sequence", "=", $result["contact"],"0","10");
echo '<select name="contactsequence" id="contactsequence">';
foreach($names AS $name){
echo '<option value="">'.$name['forename'].'</option>';
}
echo '</select>';
Change the function to return the results as a variable, rather than echo them.
function ContactLookup ($column, $clause, $value, $limit1=0, $limit2=1) {
global $conn;
$ContactLookup_Sql= "select * from contacts where $column $clause $value LIMIT $limit1, $limit2";
$ContactLookup_Rs = mysql_query($ContactLookup_Sql,$conn);
$results=array();
while($ContactLookup_Result = mysql_fetch_array($ContactLookup_Rs))
{
$results[] = array('forename'=>$ContactLookup_Result["forename"],'surname'=>$ContactLookup_Result["surname"];
}
return $results;
}
Then in your display loop,
<?php $contacts=ContactLookup("company_sequence", "=", $result["contact"],"0","10"); ?>
<select name="contactsequence" id="contactsequence">
foreach($contacts as $k=>$contact){?>
<option value="<?php echo $k;?>"><?php echo $contact['forename']; ?></option>
<?php
}
</select>

Categories