Income tax calculation using different slabs in php - php

I am trying to do a work on TAX CALCULATION using php.The required slabs or criterion for the tax calculation is based on AGE ,startincome and endincome . I am using CODEIGNITER framework.As I am new to this I have no idea on how to get the things done.
My code should contain only dynamic variables as the 'slabs' that are to be get from the Database and result should be produced based on the AGE and Salary given at random.
My view file is given below:tax.php
<form>
<table border="1" align="center" cellpadding="30">
<tr>
<td colspan="2" align="center">
<b>Tax calculation</b>
</td>
</tr>
<tr>
<td>
<label for="name"><b>Name</label>
</td>
<td>
<input id="name" name="name" type="textbox" placeholder="enter your name" size="30" >
</td>
</tr>
<tr>
<td>
<label for="name"><b>Age</label>
</td>
<td>
<input id="name" name="name" type="textbox"placeholder="enter your age" size="30" >
</td>
</tr>
<tr>
<td>
<label for=""><b>Salary:</label></td>
<td>
<input id="salary" name="phone" type="textbox"placeholder="enter your yearly salary" size="30" >
</tr>
<tr>
<td>
<div>
<input type="submit" value="calculate" name="submit" />
</div>
</td>
<td>
<label for=""><strong>Tax Amount:</strong></label>
<input id="Tax" name="tax" type="textbox" size="17" >
</td>
</table>
</form>
My controller code is below:Tax.php
<?php
class Tax extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
}
public function index()
{
$servername='localhost';
$username='root';
$password='';
$database='register';
$conn = mysqli_connect($servername,$username,$password);
$this->load->view('tax');
//$this->load->model(Taxmodel);
if(isset($_POST['submit']))
{
//echo"inside submit";
$this->form_validation->set_rules('name','Name','trim|required');
$this->form_validation->set_rules('age','Age','trim|required');
$this->form_validation->set_rules('salary','Salary','trim|required',array('required' => 'You must provide a %s.'));
//checks whether the validation returns true or false
if ($this->form_validation->run() ==TRUE)
{
//echo' validation check';
//storing data to Array
$userdata = array(
'Name' => $this->input->post('name'),
'Age' => $this->input->post('age'),
'Salary' => $this->input->post('salary')
);
print_r($userdata);
$this->load->model('Taxmodel');
//$this->Taxmodel->insertdata($userdata);
}
}
}
public function getresult()//to get database values in a row
{
echo "inside getresult";
$salary=$_POST['salary'];
$data= $this->db->query("SELECT * FROM `admin_income` WHERE age<".$age." and age in (SELECT max(age) FROM `admin_income` WHERE age<".$age." order by `age` desc) order by `age` desc ");
print_r($data);
$result=$conn->query($data);
Global $totaltax;
while ($row = mysql_fetch_assoc($result))
{echo "inside while1";
while($salary>= $row[$start_incom] && $salary< $row[$end_incom])
{
//echo"Inside tax calculation";
$diff=$salary-$startincome;
$tax=(($percentage/100)*$diff);
echo $tax;
}
echo $tax;
}
}
public function extamount()
{//to get the additional amount to be added
/*$query = $this->db->query("SELECT * FROM admin_income LIMIT 1;");
if ($query->num_rows() > 0)
{
$row = $query->next_row('array')*/
if($initial_income>$start_incom)//codnition for checking whether the salary exceeds first slab
{
$diffresult=$end_incom-$start_incom;
$adtntax=[($percentage/100)*$diffresult];
echo $adtntax;
}
$totaltax=$adtntax+$tax;
//}
}
}
?>
My model name is Taxmodel.php
Database Table
I am new to CodeIgniter. Help will be appreciated.

I have try this code and work for me you can take it as a reference. create range array like
$getTaxCharge = array(
array(
'amount_range_from' => 0,
'amount_range_to' => 250000,
'tax_percentage' => 0
),
array(
'amount_range_from' => 250001,
'amount_range_to' => 500000,
'tax_percentage' => 10
),
array(
'amount_range_from' => 500001,
'amount_range_to' => 1000000,
'tax_percentage' => 20
),
array(
'amount_range_from' => 1000001,
'amount_range_to' => 100000000000,
'tax_percentage' => 30
)
);
<?php
$getTaxCharge = array(
array(
'amount_range_from' => 0,
'amount_range_to' => 250000,
'tax_percentage' => 0,
),
array(
'amount_range_from' => 250001,
'amount_range_to' => 500000,
'tax_percentage' => 10,
),
array(
'amount_range_from' => 500001,
'amount_range_to' => 1000000,
'tax_percentage' =>20,
),
array(
'amount_range_from' => 1000001,
'amount_range_to' => 100000000000,
'tax_percentage' =>30,
)
);
$calculateTaxOnAmount = 900000;
$remainingAmount = $calculateTaxOnAmount;
$amount = $calculateTaxOnAmount;
$arrayAmount = array();
foreach ($getTaxCharge as $key => $value) {
$resultArray = array();
if ($calculateTaxOnAmount > $value['amount_range_to']) {
$sum = $value['amount_range_to'] - $value['amount_range_from'];
$resultArray['amount'] = $sum;
$resultArray['percentage'] = $value['tax_percentage'];
array_push($arrayAmount, $resultArray);
$remainingAmount = $remainingAmount - $sum;
} else {
$resultArray['amount'] = $remainingAmount;
$resultArray['percentage'] = $value['tax_percentage'];
array_push($arrayAmount, $resultArray);
break;
}
}
$resultantTaxAmount = 0;
foreach ($arrayAmount as $key => $value) {
$cal = (($value['amount'] * $value['percentage']) / 100);
$resultantTaxAmount = $resultantTaxAmount + $cal;
}
echo round($resultantTaxAmount);
?>

Related

Codeigniter : how to create dynamic dropdown

So i tried to create a dynamic dropdown in the form page, while user filling the form, there will be a dynamic dropdown for user to select a certain/specific thing, once it's selected, it can be saved into the database. But when i testing it, the dynamic dropdown show nothing, how can i fix it??
The model :
public function get_jenis_pekerjaan(){
$query = $this->db->get('jenis_pekerjaan');
return $query->result_array();
}
The Controller :
public function job_type(){
$data['jenis_pekerjaan'] = $this->m_lowongan->get_jenis_pekerjaan();
$this->load->view('create_lowongan', $data);
}
public function store_lowongan(){
$user_name = $this->session->userdata('name');
$title = $this->input->post('title');
$lokasi = $this->input->post('lokasi');
$level_pekerja = $this->input->post('jenis_pekerjaan');
$pengalaman_kerja = $this->input->post('pengalaman_kerja');
$pendidikan = $this->input->post('pendidikan');
$alamat = $this->input->post('alamat');
$no_wa = $this->input->post('no_wa');
$no_telp = $this->input->post('no_telp');
$min_gaji = $this->input->post('min_gaji');
$max_gaji = $this->input->post('max_gaji');
$job_desc = $this->input->post('job_desc');
$created_at = date('y-m-d');
$status = 'draft';
$data = array(
'user_name' => $user_name,
'title' => $title,
'lokasi' => $lokasi,
'level_pekerja' => $level_pekerja,
'pengalaman_kerja' => $pengalaman_kerja,
'pendidikan' => $pendidikan,
'alamat' => $alamat,
'no_wa' => $no_wa,
'no_telp' => $no_telp,
'min_gaji' => $min_gaji,
'max_gaji' => $max_gaji,
'job_desc' => $job_desc,
'created_at' => $created_at,
'status' => $status,
);
$this->m_lowongan->input_data($data, 'lowongan');
redirect ('dashboard');
}
The view :
<tr>
<td>Level Pekerjaan</td>
<td>
<select name="jenis_pekerjaan" id="jenis_pekerjaan" class="form-control">
<?php foreach($jenis_pekerjaan as $l) {?>
<option value="<?php echo $l['jenis_pekerjaan']?>"><?php echo $l['jenis_pekerjaan']?></option>
<?php }?>
</select>
</td>
</tr>
I think I made it work by doing this.
I create a function to get the data in the model:
public function get_jenis_pekerjaan(){
return $this->db->get('jenis_pekerjaan');
}
I call that function into my controller:
public function create_lowongan() {
$data['jenis_pekerjaan'] = $this->m_lowongan->get_jenis_pekerjaan()->result();
$this->load->view('create_lowongan', $data);
}
I add the $data_jp in my store function to store the value of jenis_pekerjaan:
public function store_lowongan() {
$data_jp['jenis_pekerjaan'] = $this->m_lowongan->get_jenis_pekerjaan();
$user_name = $this->session->userdata('name');
$title = $this->input->post('title');
$lokasi = $this->input->post('lokasi');
$level_pekerja = $this->input->post('jenis_pekerjaan');
$pengalaman_kerja = $this->input->post('pengalaman_kerja');
$pendidikan = $this->input->post('pendidikan');
$alamat = $this->input->post('alamat');
$no_wa = $this->input->post('no_wa');
$no_telp = $this->input->post('no_telp');
$min_gaji = $this->input->post('min_gaji');
$max_gaji = $this->input->post('max_gaji');
$job_desc = $this->input->post('job_desc');
$created_at = date('y-m-d');
$status = 'draft';
$data = array(
'user_name' => $user_name,
'title' => $title,
'lokasi' => $lokasi,
'level_pekerja' => $level_pekerja,
'pengalaman_kerja' => $pengalaman_kerja,
'pendidikan' => $pendidikan,
'alamat' => $alamat,
'no_wa' => $no_wa,
'no_telp' => $no_telp,
'min_gaji' => $min_gaji,
'max_gaji' => $max_gaji,
'job_desc' => $job_desc,
'created_at' => $created_at,
'status' => $status,
);
$this->m_lowongan->input_data($data, 'lowongan');
redirect ('dashboard');
}
I edit the view so it looks like this for the dynamic dropdown:
<tr>
<td>Level Pekerjaan</td>
<td>
<select name="jenis_pekerjaan" id="jenis_pekerjaan" class="form-control">
<?php foreach($jenis_pekerjaan as $l) {?>
<option value="<?php echo $l->job_type?>"><?php echo $l->job_type?></option>
<?php }?>
</select>
</td>
</tr>
And it work, it show the value from jenis_pekerjaan table, and it store the data into the database :D

How to draw a table with data from Mysql?

I have obtained the following data through Mysql.
idx item_name parent_id
44 'A' -1
46 'B' -1
47 'C' 44
48 'D' 44
49 'E' 44
50 'F' 46
51 'G' 47
52 'H' 47
53 'I' 48
I want to draw a table using this data.
I've searched for information, but it's very difficult.
Is there anyone who can help me?
Example
<table>
<thead>
<tr>
<th>item1</th>
<th>item2</th>
<th>item3</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td rowspan="4">A</td>
<td rowspan="2">C</td>
<td>G</td>
<td>-</td>
</tr>
<tr>
<td>H</td>
<td>-</td>
</tr>
<tr>
<td>D</td>
<td>I</td>
<td>-</td>
</tr>
<tr>
<td>E</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td>B</td>
<td>F</td>
<td>-</td>
<td>-</td>
</tr>
</tbody>
Is there a PHP library related to this?
=========================================
The values in the database consist of a passenger structure. (Parent ID Existence)
I want to make this data into a table using PHP.
"Rowspan" will be used to accommodate the number of children.
However, this method of HTML coding is very difficult.
I need a library or a related example code.
Here you go, the code that I made to solve your problem.
It is not perfect but I hope you got the idea.
Your problem cannot be solved by a simple array loop, because your data is not a simple table but a tree. Therefore, using recursive loop to walk through the data is one of the solutions.
<?php
// the data, should be obtained from your database
// to simplify the code, I made them into an array of objects
$rows[] = (object) array( 'idx' => 44, 'name' => 'A', 'pid' => -1 );
$rows[] = (object) array( 'idx' => 46, 'name' => 'B', 'pid' => -1 );
$rows[] = (object) array( 'idx' => 47, 'name' => 'C', 'pid' => 44 );
$rows[] = (object) array( 'idx' => 48, 'name' => 'D', 'pid' => 44 );
$rows[] = (object) array( 'idx' => 49, 'name' => 'E', 'pid' => 44 );
$rows[] = (object) array( 'idx' => 50, 'name' => 'F', 'pid' => 46 );
$rows[] = (object) array( 'idx' => 51, 'name' => 'G', 'pid' => 47 );
$rows[] = (object) array( 'idx' => 52, 'name' => 'H', 'pid' => 47 );
$rows[] = (object) array( 'idx' => 53, 'name' => 'I', 'pid' => 48 );
// Build Tree
foreach($rows as $r) {
$r->child = [];
foreach($rows as $c) {
if($r->idx == $c->idx) continue;
if($c->pid == $r->idx)
$r->child[] = $c;
}
}
// recursive walk through the trees to set maxLevel and nodeLevel
function cLeaves($node, $level, &$maxLevel) {
$count = 0;
if(count($node->child) == 0) {
$node->span = 1;
$node->level = $level;
$maxLevel = $maxLevel < $level ? $level : $maxLevel;
return 1;
} else {
$node->level = $level;
$level++;
foreach($node->child as $c) {
$count += cLeaves($c, $level, $maxLevel);
}
$node->span = $count;
return $count;
}
}
// recursive walk through the trees to draw table
function drawTable($cnode, $maxLevel) {
echo '<td rowspan="'.$cnode->span.'">'.$cnode->name.'</td>';
if(count($cnode->child) == 0) {
if($cnode->level < $maxLevel) {
for($i = $cnode->level; $i<$maxLevel; $i++)
echo '<td>-</td>';
}
echo '<td>-</td>'; // for the value column
echo '</tr>';
return;
}
foreach($cnode->child as $c) {
drawTable($c, $maxLevel);
}
}
// update the data structure
$maxLevel = 0;
foreach($rows as $r) {
if($r->pid == -1) {
$level = 0;
$r->span = cLeaves($r, $level, $maxLevel);
$r->level = $level;
}
}
echo '<table border="1">';
echo '<tr>';
// draw table's title row
for($i = 0; $i <= $maxLevel; $i++) {
echo '<td>item'.($i+1).'</td>';
if($i == $maxLevel) echo '<td>value</td>';
}
echo '</tr>';
// draw tree on table format
foreach($rows as $r) {
if($r->pid == -1) {
echo '<tr>';
drawTable($r, $maxLevel);
}
}
echo '</table>';
?>
If you run the code, the result would be something like below:
What I still remember from PHP is, you can use for loop and put one of these rows into the php <tag>. Then use your SELECT query to get each tuple from MySql into each tuple's cells in this tag:
<tr>
<td> Cell value using Sql Select statement</td>
<td> Cell value using Sql Select statement</td>
<td> Cell value using Sql Select statement</td>
</tr>
You can do this process n of times depend on the No. Of rows you want to insert into the table.
Then, close your **PHP <tag>.
you can use mysqli_fetch_assoc to fetch your data from the database and run a loop to format it using html table:
<table border=1>
<thead>
<tr>
<th>idx</th>
<th>item_name</th>
<th>parent_id</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("localhost", "root", "", "yourdatabase");
$table = mysqli_query($con, "SELECT idx, item_name, parent_id FROM mytable");
while ($record = mysqli_fetch_assoc($table)) {
echo "<tr>";
echo "<td>" . $record["idx"] . "</td>";
echo "<td>" . $record["item_name"] . "</td>";
echo "<td>" . $record["parent_id"] . "</td>";
echo "</tr>";
}
?>
</tbody>
If you want to use a library, you can check codeigniter (PHP framework)'s table helper.
https://codeigniter.com/userguide3/libraries/table.html
$this->table->generate($table);

PHP: shopping cart empty after clicking the add button

As per title, I have a problem when adding products to the cart: it would show a window message that says that the product has been added, but in truth it is not there. It gives the following error:
Fatal error: Cannot use object of type stdClass as array
the line is: <td><?php echo $value['item_name']; ?></td>
Here is the code file reserve.php :
<?php
session_start();
ini_set('display_errors', 1);
$connect = mysqli_connect('127.0.0.1', 'root', '***********', 'Community Garden List');
if (isset($_POST['add'])) {
if (isset($_SESSION['cart'])) {
$item_array_id = array_column($_SESSION['cart'], 'product_id');
if (!in_array($_GET['id'], $item_array_id)) {
$count = count($_SESSION['cart']);
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity'],
);
$_SESSION['cart'][$count] = $item_array;
echo '<script>window.location="reserve.php"</script>';
} else {
echo '<script>alert("Product is already Added to Cart")</script>';
echo '<script>window.location="reserve.php"</script>';
}
} else {
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity'],
);
$_SESSION['cart'][0] = $item_array;
}
}
if (isset($_GET['action'])) {
if ($_GET['action'] == 'delete') {
foreach ($_SESSION['cart'] as $keys => $value) {
if ($value['product_id'] == $_GET['id']) {
unset($_SESSION['cart'][$keys]);
echo '<script>alert("Product has been Removed...!")</script>';
echo '<script>window.location="reserve.php"</script>';
}
}
}
}
?>
?>
html code
<?php
$query = 'SELECT * FROM product ORDER BY serial ASC';
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
?>
<div class="col-md-4">
<form method="post" action="reserve.php?action=add&id='.$row['id'].">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<img src="<?php echo $row['image']; ?>" class="img-responsive" style="width:100%;>
<h5 class="text-info"><?php echo $row['pname']; ?></h5>
<h5 class="text-danger">€ <?php echo $row['price']; ?></h5>
<h5 class="text-info"><?php echo $row['pdescription']; ?></h5>
<input type="text" name="quantity" class="form-control" value="1">
<input type="hidden" name="hidden_name" value="<?php echo $row['pname']; ?>">
<input type="hidden" name="hidden_price" value="<?php echo $row['price']; ?>">
<input type="hidden" name="hidden_pdescription" value="<?php echo $row['pdescription']; ?>">
<input type="submit" name="add" style="margin-top:5px;" class="btn btn-success" value="Add to Bag">
</div>
</form>
</div>
}
}
?>
<?php
if(!empty($_SESSION["cart"])){
$total = 0;
foreach ($_SESSION["cart"] as $key => $value) {
?>
<tr>
<td><?php echo $value["item_name"]; ?></td>
<td><?php echo $value["item_quantity"]; ?></td>
<td>$ <?php echo $value["product_price"]; ?></td>
<td>
$ <?php echo number_format($value["item_quantity"] * $value["product_price"], 2); ?></td>
<td><a href="Cart.php?action=delete&id=<?php echo $value["product_id"]; ?>"><span
class="text-danger">Remove Item</span></a></td>
</tr>
<?php
$total = $total + ($value["item_quantity"] * $value["product_price"]);
}
?>
<tr>
<td colspan="3" align="right">Total</td>
<th align="right">$ <?php echo number_format($total, 2); ?></th>
<td></td>
</tr>
<?php
}
?>
</table>
</div>
</div>
I've tried print "<pre>"; var_dump($row); exit; after this line: foreach e($_SESSION['cart'] as $key => $value) { and it comes a table with NULL inside. What does that mean?
Before that, i tried to change $value['item_name'] with $value->item_name , and i got the following error:
Notice: Undefined property: stdClass::$item_name in
Will you please help me to understand what's wrong? thank you.
i solve some errors try to assemble the parts in the right places
i put all content modified here you should copy paste parts you need.
<?php
session_start();
ini_set('display_errors', 1);
$connect = mysqli_connect('127.0.0.1', 'root', '******************', 'Community Garden List');
if (isset($_POST['add'])) {
if (isset($_SESSION['cart'])) {
$item_array_id = array_column($_SESSION['cart'], 'product_id');
if (!in_array($_GET['id'], $item_array_id)) {
$count = count($_SESSION['cart']);
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity']//!!!,
);
$_SESSION['cart'][$count] = $item_array;
//echo '<script>window.location="reserve.php"</script>';// do not send content when you use sessions $_SESSION['cart'][0] = $item_array;
} else {
// echo '<script>alert("Product is already Added to Cart")</script>';
//echo '<script>window.location="reserve.php"</script>';
}
} else {
$item_array = array(
'product_id' => $_GET['id'],
'item_name' => $_POST['hidden_name'],
'product_price' => $_POST['hidden_price'],
'item_quantity' => $_POST['quantity']//!!!!!!!!!!!! ? ->,
);
$_SESSION['cart'][0] = $item_array;
}
}
if (isset($_GET['action'])) {
if ($_GET['action'] == 'delete') {
foreach ($_SESSION['cart'] as $keys => $value) {
if ($value['product_id'] == $_GET['id']) {
unset($_SESSION['cart'][$keys]);
echo '<script>alert("Product has been Removed...!")</script>';
echo '<script>window.location="reserve.php"</script>';
}
}
}
}
$query = 'SELECT * FROM product ORDER BY serial ASC';
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
die();
$tmimi1=<<<mimi1
<div class="col-md-4">
<form method="post" action="reserve.php?action=add&id={$row['id']}">
<div style="border: 1px solid #eaeaec; margin: -1px 19px 3px -1px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); padding:10px;" align="center">
<img src="{$rr1}" class="img-responsive" style="width:100%;">
<h5 class="text-info">{$row['pname']}</h5>
<h5 class="text-danger">€{$row['price']}</h5>
<h5 class="text-info">{$row['pdescription']}</h5>
<input type="text" name="quantity" class="form-control" value="1">
<input type="hidden" name="hidden_name" value="{$row['pname']}">
<input type="hidden" name="hidden_price" value="{$row['price']}">
<input type="hidden" name="hidden_pdescription" value="{$row['pdescription']}">
<input type="submit" name="add" style="margin-top:5px;" class="btn btn-success" value="Add to Bag">
</div>
</form>
</div>
mimi1;
}
}
echo($tmimi1);
if(!empty($_SESSION["cart"])){
$total = 0;
foreach ($_SESSION["cart"] as $key => $value) {
$tmimi2 =<<<mimi2
<tr>
<td>{$value["item_name"]}</td>
<td>{$value["item_quantity"]}</td>
<td>${$value["product_price"]}</td>
<td>$
mimi2;
echo($tmimi2);
echo number_format($value["item_quantity"] * $value["product_price"], 2);
$tmimi2=<<<mimi3
</td>
<td><a href="Cart.php?action=delete&id={$value["product_id"]}"><span
class="text-danger">Remove Item</span></a></td>
</tr>
mimi3;
echo($tmimi3);
$total = $total + ($value["item_quantity"] * $value["product_price"]);
}
$tmimi2=<<<mimi4
<tr>
<td colspan="3" align="right">Total</td>
<th align="right">$
mimi4;
echo($tmimi4);
echo number_format($total, 2);
$tmimi2=<<<mimi5
</th>
<td></td>
</tr>
mimi5;
echo($tmimi5); }
$tmimi2=<<<mimi6
</table>
</div>
</div>
mimi6;
echo($tmimi6);
?>
you deleted your post about grab an array from online weather data before to post you the answer? i don't know how to send you what you ask and then you delete the question before to push 'post the answer' button!(if was you mimi who ask or there is another mimi=not sure) in case you ask before that i post you the answer:
<?php
function print_r2($var){
echo('<h3>'.$var.':</h3><br>');
print_r($GLOBALS[$var]);echo('br');
}
function hr(){
echo('<hr>');
}
$lines=implode(file('http://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22'));
print_r2('lines');hr();
$data = json_decode($lines);
print_r2('data');hr();
print('wind obj:');print_r($data->wind);hr();
print('speed:');print_r($data->wind->speed);hr();
print('deg:');print_r($data->wind->deg);hr();
?>
and on my screen i got ..push RUN CODE SNIPPET!
<h3>lines:</h3><br>{"coord":{"lon":139.01,"lat":35.02},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"base":"stations","main":{"temp":285.514,"pressure":1013.75,"humidity":100,"temp_min":285.514,"temp_max":285.514,"sea_level":1023.22,"grnd_level":1013.75},"wind":{"speed":5.52,"deg":311},"clouds":{"all":0},"dt":1485792967,"sys":{"message":0.0025,"country":"JP","sunrise":1485726240,"sunset":1485763863},"id":1907296,"name":"Tawarano","cod":200}br<hr><h3>data:</h3><br>stdClass Object
(
[coord] => stdClass Object
(
[lon] => 139.01
[lat] => 35.02
)
[weather] => Array
(
[0] => stdClass Object
(
[id] => 800
[main] => Clear
[description] => clear sky
[icon] => 01n
)
)
[base] => stations
[main] => stdClass Object
(
[temp] => 285.514
[pressure] => 1013.75
[humidity] => 100
[temp_min] => 285.514
[temp_max] => 285.514
[sea_level] => 1023.22
[grnd_level] => 1013.75
)
[wind] => stdClass Object
(
[speed] => 5.52
[deg] => 311
)
[clouds] => stdClass Object
(
[all] => 0
)
[dt] => 1485792967
[sys] => stdClass Object
(
[message] => 0.0025
[country] => JP
[sunrise] => 1485726240
[sunset] => 1485763863
)
[id] => 1907296
[name] => Tawarano
[cod] => 200
)
br<hr>wind obj:stdClass Object
(
[speed] => 5.52
[deg] => 311
)
<hr>speed:5.52<hr>deg:311<hr>

Trying to print values returned from multidimentional array as dropdown in codeigniter

No able to display firstname and lastname as dropdown in codeigniter view. Now its displaying blank dropdown. Attached MVC code for reference. Model is returning the correct data i.e when i try to do this print_r($data['groups']);
die; in my controller it gives the output as below
Array ( [0] => Array ( [id] => 62 [userid] => 67 [emp_code] => 050 [emp_shift] => General Shift [emp_category] => Full Time [cccode] => [prefix] => Mr. [firstname] => Divya [middlename] => [lastname] => Darshini [designation_id] => 9 [division_id] => [branch_id] => 5 [company] => [email] => shashankbhat11#gmail.com [personal_email] => [nickname] => [url] => [birthday] => 23-09-1990 [panno] => [passportno] => [passportdate] => [joining_date] => 08-07-2016 [resignation_date] => [team_id] => [tag_ids] => [im] => [facebook] => [twitter_handle] => [linkedin_id] => [instagram] => [googleplus] => [maidenname] => [profileimage] => [blood_group] => B Positive [gender] => Female [married] => [anniversary] => 01-01-1970 [ctc] => [mood] => [doc_type] => [org_to] => [org_from] => [org] => [role_title] => [org_skills] => [scanned_doc_work] => [pass_year] => [adm_year] => [degree] => [univ] => [edu_scanned_doc] => [declare_home] => [declare_menu1] => [declare_family] => [declare_menu4] => [declare_menu7] => [declare_menu8] => [declare_menu2] => [declare_menu3] => [s_cluster_id] => 1 [status] => 1 [deleted] => 0 [registrationtime] => 1466579573 [timemodified] => 0 [modifierid] => 0 [alternate_email] => [notice_period] => 0 ) )
I am just trying to print the firstname and lastname as dropdown values.
My view code is:
<table>
<tr>
<td>
Name
</td>
<td>
<select class="form-control" name="name">
<?php
foreach($groups as $row){
echo '<option value="'.$row->firstname.'">'.$row->firstname.' '.$row->lastname.'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>
Exit Type
</td>
<td>
<select class="form-control" id="security_question_1" name="exit_type">
<option name="exit_type" value="" selected>Select a option</option>
<option name="exit_type" value="Absconding">Absconding</option>
</select>
</td>
</tr>
<tr></tr>
<tr>
<td>
<label>Absconding Since</label>
</td>
<td>
<div class="date" data-date="12-02-2012" data-date-format="mm-dd-yyyy" data-date-viewmode="years">
<input placeholder="Absconding Since" class=" m-wrap col-md-8 form-control " id="enddt" type="text" name="abscondingsince" value="<?php if($row->requested_date!='') echo date("d-m-Y",$row->requested_date); ?>" required/>
</td>
</tr>
<tr>
<td>
<label>Date of contact via Phone</label>
</td>
<td>
<div class="date" data-date="12-02-2012" data-date-format="mm-dd-yyyy" data-date-viewmode="years">
<input placeholder="Date of contact via Phone" class=" m-wrap col-md-8 form-control " id="enddtt" type="text" name="dateofcontactviaphone" value="<?php if($row->requested_date!='') echo date("d-m-Y",$row->requested_date); ?>" required/>
</td>
</tr>
<td>
<label>
Response/Outcome from attempt to contact through phone
</label>
</td>
<td>
<textarea class="form-control" name="commentsphone"></textarea>
</td>
<tr>
<td>
<label>Date of contact via email</label>
</td>
<td>
<div class="date" data-date="12-02-2012" data-date-format="mm-dd-yyyy" data-date-viewmode="years">
<input placeholder="Date of contact via email" class=" m-wrap col-md-8 form-control " id="enddttt" type="text" name="dateofcontactviaemail" value="<?php if($row->requested_date!='') echo date("d-m-Y",$row->requested_date); ?>" required/>
</td>
</tr>
<td>
<label>
Response/Outcome from attempt to contact through email
</label>
</td>
<td>
<textarea class="form-control" name="commentsemail"></textarea>
</td>
<tr>
<td>
Attach Email Sent to Employee<input multiple="multiple" name="userfile1[]" size="20" type="file" />
</td>
<td>
Attach Phone Logs made to Employee<input multiple="multiple" name="userfile2[]" size="20" type="file" />
</td>
</tr>
</tr>
</table>
My controller code is :
function manager_add_absconding(){
global $SITE,$USER;
$data = array();
$data['row'] = new stdClass();
$data['row'] = $this->admin_init_elements->set_post_vals($this->input->post());
$data['offices']=$this->mod_common->get_all_offices();
$clients = currentuserclients();
$data['roles'] = $this->mod_common->get_cat_array('designation','status',"1' AND id > '0",'designation');
$data['reasons'] = $this->exit_common->get_all_reasons();
$id = $this->uri->segment(3);
//$data['roles'] = $this->exit_common->get_cat_array('designation','status',"1' AND id > '0",'designation');
get_city_state_country_array($data,array('cityid'=>$data['row']->cityid));
$data['error_message'] = '';
$data['row']->id = $this->uri->segment(3);
$data['id'] = $this->uri->segment(3);
$data['action'] = 'add';
$data['heading'] = 'Add';
$data['msg_class'] = 'sukses';
$data['path']=$path;
$post_action = $this->input->post('action');
if($post_action=='add' || $post_action =='update' ){
$post_array = $this->input->post();
$action = ($post_action == 'add')?'inserted':'updated';
//echo '<pre>';print_r($SITE);die;
$post_array['exit_type'] = 'Employee Initiated';
$data['managerid'] = $this->exit_common->get_managerids($id);
$data['error_message'] = $this->exit_common->add_new_absconding_alert($post_array,$action);
if($data['error_message'] == 'Record '.$action.' successfully'){
$data['row'] = new stdClass();
$data['row']->id = $this->uri->segment(3);
$data['row']->status = 1;
}
}
$data['grievance_types'] = $this->mod_common->get_user_allowed_leaves();
if($data['row']->id>0){
$data['action'] = 'update';
$data['heading'] = 'Edit';
$data['rows'] = $this->mod_common->get_leave_request($data['row']->id);
$clid = $data['row']->id;
$data['row']->id = $clid;
}
//$data['my_detail'] = $this->mod_common->get_my_details($USER->id);
$data['my_detail'] = $this->exit_common->get_details_profile($USER->id,'users_details','userid');
$data['my_detail']->userdetail = $this->exit_common->get_details($USER->id,'users');
get_address($data['my_detail'],ADDRESS_TYPE1,$USER->id);
$data['cities']=$this->exit_common->get_array_frontend('city');
$data['notice_period']=$this->exit_common->get_notice_period($USER);
$data['groups'] = $this->exit_common->get_all_names_by_user($USER);
$this->data['maincontent'] = $this->load->view('maincontents/manager_add_new_exit', $data,true);
$this->load->view('layout', $this->data);
}
My model code is :
function get_all_names_by_user($USER){
$this->db->select('g.*,firstname,lastname');
$this->db->from('pr_users_details as g');
$this->db->where('userid', $USER->id);
//$this->db->join($this->myTables['pr_users_details'].' as ud','ud.userid = g.userid');
//$this->db->join('pr_users_details as ud','ud.userid = g.userids');
/* $this->db->join($this->myTables['users_details'].' as ud','ud.userid = g.userid');
$this->db->join('pr_resignation_type as gt','gt.id = g.sr_type');*/
$query=$this->db->get();
$return = $query->result_array();
return $return;
}
Change your code to
function get_all_names_by_user($USER){
$this->db->select('g.*,firstname,lastname');
$this->db->from('pr_users_details as g');
$this->db->where('userid', $USER->id);
//$this->db->join($this->myTables['pr_users_details'].' as ud','ud.userid = g.userid');
//$this->db->join('pr_users_details as ud','ud.userid = g.userids');
/* $this->db->join($this->myTables['users_details'].' as ud','ud.userid = g.userid');
$this->db->join('pr_resignation_type as gt','gt.id = g.sr_type');*/
$query=$this->db->get();
$return = $query->result();
return $return;
}
Just change the $return = $query->result_array(); to $return = $query->result();
For example if you are using result_array() then the would be like
$query = $this->db->query("YOUR QUERY");
foreach ($query->result_array() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
where as for result() it would be
$query = $this->db->query("YOUR QUERY");
foreach ($query->result() as $row)
{
echo $row->title;
echo $row->name;
echo $row->body;
}
Refrence:- https://www.codeigniter.com/userguide3/database/results.html
use codeigniter's inbuilt dropdown function instead of html select tag.
<?php
$attributes = 'class = "form-control" id = "group"';
echo form_dropdown('group',$group,set_value('firstname'),$attributes);
?>

json_encode from php array: how do I adjust my php so my array is correct?

I am trying to create a php array from posted values and then json_encode to achieve this:
[{"network_type":"facebook","network_url":"fb.com/name"},{"network_type":"twitter","network_url":"#name"},{"network_type":"instagram","network_url":"#name"}]
which after json_decode looks like:
array(
[0] => stdClass(
network_type = 'facebook'
network_url = 'fb.com/name'
)
[1] => stdClass(
network_type = 'twitter'
network_url = '#name'
)
[2] => stdClass(
network_type = 'instagram'
network_url = '#name'
)
)
My php looks like this:
$social_data = array(
'network_type' => $this->input->post('network_type'),
'network_url' => $this->input->post('network_url')
);
and so the array is not grouped the way I want it, but rather by the field name:
array(
['network_type'] => array(
[0] => 'facebook'
[1] => 'twitter'
[2] => 'instagram'
)
['network_url'] => array(
[0] => 'fb.com/name'
[1] => '#name'
[2] => '#name'
)
and therefore the result of the json_encode isn't grouped how I want it:
{"network_type":["facebook","twitter","instagram"],"network_url":["fb.com/name","#name","#name"]}
)
So the question is...how do I adjust my php so the array is correct?
--- here's the input fields:
<?php
foreach ($social as $key => $value) {?>
<p>
<label for="network_type"><input type="text" size="20" name="network_type[]" value="<?php echo $value -> network_type; ?>" placeholder="Social Network" /></label>
<label for="network_url"><input type="text" size="20" name="network_url[]" value="<?php echo $value -> network_url; ?>" placeholder="URL or Handle" /></label>
<a class="remNetwork" href="#">Remove</a>
</p>
<?php } ?>
----latest update: this is sooooo close!-----
Ok, for some reason (probably me botching things one way or another), both suggested methods below didn't quite get me there....but, a mix of both methods has gotten me close:
This if/loop/array setup:
$network_type = (array)$this->input->post('network_type', true);
$network_url = (array)$this->input->post('network_url', true);
$social_data = array();
if (($counter = count($network_type)) == count($network_url)){
for($i = 0;$i < $counter; $i++) {
$social_data[$i] = array(
'network_type' => $this->input->post('network_type[$i]'),
'network_url' => $this->input->post('network_url[$i]'),
);
}
}
paired with this input loop:
<?php
foreach ($social as $key => $value) {
?>
<p>
<label for="network_type"><input type="text" size="20" name="network_type[]" value="<?php echo $value -> network_type; ?>" placeholder="Social Network" /></label>
<label for="network_url"><input type="text" size="20" name="network_url[]" value="<?php echo $value -> network_url; ?>" placeholder="URL or Handle" /></label>
<a class="remNetwork" href="#">Remove</a>
</p>
<?php } ?>
is yielding the following:
array(
[0] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
[1] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
[2] => array(
['network_type'] => FALSE
['network_url'] => FALSE
)
)
So, I think if I can figure out why these values are false, then we've done it!
Thanks and appreciation for your patience and help in advance...
-- update again ----
To my dismay, I've left out a piece that's perhaps critical...the coffee script that's dynamically creating the form fields when there's more than one social:
$ ->
socialDiv = $("#social")
i = $("#social p").size() + 1
index = 0
$("#addNetwork").click ->
$("<p><label for=\"network_type[]\"><input type=\"text\" id=\"network_type[]\" size=\"20\" name=\"network_type[]\" value=\"\" placeholder=\"Social Network\" /></label><label for=\"network_url[]\"><input type=\"text\" id=\"network_url[]\" size=\"20\" name=\"network_url[]\" value=\"\" placeholder=\"URL or Handle\" /></label> Remove</p>").appendTo socialDiv
i++
false
$(document).on "click", ".remNetwork", ->
#$(".remNetwork").bind "click", ->
if i > 1
$(this).parent("p").remove()
i--
false
In your example, i can asume that network_type and network_url are inputs like:
<input type="text" name="network_type[]" /> and <input type="text" name="network_url[]" />
so in order to accomplish what you want you would:
<?php
$networkType = (array)$this->input->post('network_type', true);
$networkUrl = (array)$this->input->post('network_url', true);
$networkData = array();
if (($counter = count($networkType)) == count($networkUrl)) {
for ($i = 0; $i < $counter; ++$i) {
$networkData[] = array(
'network_type' => $networkType[$i],
'network_url' => $networkUrl[$i]
);
}
}
?>
and should give you the desired json.
However, this approach is a bit clunky and unreliable.
Instead, i would define the input fields like:
<input type="text" name="network[0][network_type]" /> and <input type="text" name="network[0][network_url]" />
<input type="text" name="network[1][network_type]" /> and <input type="text" name="network[1][network_url]" />
and i would generate the php array like:
<?php
$networkData = (array)$this->input->post('network', true);
?>
Just my two cents :)
L.E:
To make it detailed and create the std objects from your array, you would:
$networkData = array();
if (($counter = count($networkType)) == count($networkUrl)) {
for ($i = 0; $i < $counter; ++$i) {
$obj = new StdClass();
$obj->network_type = $networkType[$i];
$obj->network_url = $networkUrl[$i];
$networkData[] = $obj;
}
}
print_r($networkData);
You can use a for loop to iterate through as you feed them into the $social_data array. It would be
for($i = 0;$i < $items.length;$i++) {
$social_data[$i] = array(
'network_type' => $this->input->post('network_type[$i]'),
'network_url' => $this->input->post('network_url[$i]'),
);
The resulting array will look like:
$social_data[0] ->
'network_type' => 'facebook',
'network_url' => 'fbook.com/user'
$social_data[1] ->
...etc
I'm not totally sure what context you're getting the network_type and url but they will both be arrays and looping through for each individual value is what to do. Without the rest of the code it's hard to get much more specific but hopefully this will point you in the right direction.

Categories