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>
Related
This is my first question in a long time, any help is greatly appreciated!
I've got one database storing vehicles and one database storing their images. I am using an INNER JOIN to grab a list of vehicles and their images. After the database query, I put the return into an array; so 2 arrays in 1 array:
return array($vehicles, $vehicle_images);
When I do a print_r I get the correct return:
<?php print_r($your_listings[0]); ?>
<br />
<?php print_r($your_listings[1]); ?>
Returns:
Array
(
[0] => Array
(
[vehicle_id] => 35
[vehicle_type] => jeep
[vehicle_vin] => 6969
[owner_email] => user#user.com
[vehicle_make] => Jeep
[vehicle_year] => 2008
[vehicle_model] => cherokee
)
[1] => Array
(
[vehicle_id] => 36
[vehicle_type] => motorcycle
[vehicle_vin] => 1234
[owner_email] => user#user.com
[vehicle_make] => honda
[vehicle_year] => 2018
[vehicle_model] => random
)
[2] => Array
(
[vehicle_id] => 39
[vehicle_type] => atv
[vehicle_vin] => 3215
[owner_email] => user#user.com
[vehicle_make] => Yamaha
[vehicle_year] => 1990
[vehicle_model] => OHYEA
)
)
Array
(
[0] => Array
(
[vehicle_id] => 35
[image_display] => placeholder
)
[1] => Array
(
[vehicle_id] => 36
[image_display] => /new/images/vehicles/users/42/image.jpg
)
[2] => Array
(
[vehicle_id] => 36
[image_display] => /new/images/vehicles/users/42/vehicle1.jpg
)
[3] => Array
(
[vehicle_id] => 35
[image_display] => /new/images/vehicles/users/42/vehicle.jpg
)
[4] => Array
(
[vehicle_id] => 39
[image_display] => placeholder
)
)
Now when I do a foreach (including bootstrap 4 styling), it only shows 2 vehicles instead of 3; the 2 vehicles it shows appear to be showing exactly as I want them:
<div class="container-fluid">
<div class="row no-gutters">
<?php
$your_listings = owner_listings($_SESSION['user']);
if (!($your_listings[0])) {
echo '<div class="col-sm"><div class="alert alert-danger" role="alert"><i class="fas fa-exclamation"></i> You do not have any listings active at this time.</div></div>';
}
else {
foreach ($your_listings as $i => $item) {
$make = $your_listings[0][$i]['vehicle_make'];
$model = $your_listings[0][$i]['vehicle_model'];
$year = $your_listings[0][$i]['vehicle_year'];
$vehicle = $your_listings[0][$i]['vehicle_id'];
$image = $your_listings[1][$i]['image_display'];
if ($image != 'placeholder') {
echo '<div class="col-sm"><div class="card" style="width: 18rem;">
<h5 class="card-title text-center font-weight-bold">'.$year.' '.$make.' '.$model.'</h5>
<img class="card-img-top" src="'.$image.'" alt="'.$year.' '.$make.' '.$model.'">
<div class="card-body">
Edit
</div>
</div></div>';
}
else {
if ($your_listings[0][$i]['vehicle_type'] == 'atv') {
$image = '/new/images/vehicles/types/atv.png';
}
elseif ($your_listings[0][$i]['vehicle_type'] == 'jeep') {
$image = '/new/images/vehicles/types/jeep.png';
}
elseif ($your_listings[0][$i]['vehicle_type'] == 'motorcycle') {
$image = '/new/images/vehicles/types/motorchycle.png';
}
echo '<div class="col-sm"><div class="card" style="width: 18rem;">
<h5 class="card-title text-center font-weight-bold">'.$year.' '.$make.' '.$model.'</h5>
<img class="card-img-top" src="'.$image.'" alt="'.$year.' '.$make.' '.$model.'">
<div class="card-body">
Edit
</div>
</div></div>';
}
}
}
?>
</div>
</div>
Have I just been staring at this too long? What am I doing wrong? Any help is appreciated.
Thanks!
You are looping original array which has two arrays as you said. What you want is to loop through only first element of your_listings array to get three vehicles
if (!($your_listings[0])) {
echo '<div class="col-sm"><div class="alert alert-danger" role="alert"><i class="fas fa-exclamation"></i> You do not have any listings active at this time.</div></div>';
}
else {
foreach ($your_listings as $i => $item) { // should be foreach ($your_listings[0] as $i => $item) {
$make = $item['vehicle_make'];
$model = $item['vehicle_model'];
Give a try to this answer...
<div class="container-fluid">
<div class="row no-gutters">
<?php
$your_listings = owner_listings($_SESSION['user']);
if (!($your_listings[0]))
{
echo '<div class="col-sm"><div class="alert alert-danger" role="alert"><i class="fas fa-exclamation"></i> You do not have any listings active at this time.</div></div>';
}
else
{
$newarray = array();
foreach($your_listings[0] as $i => $item)
{
$newarray[$item["vehicle_id"]] = $item["image_display"];
}
foreach ($your_listings[0] as $i => $item)
{
$make = $item['vehicle_make'];
$model = $item['vehicle_model'];
$year = $item['vehicle_year'];
$vehicle = $item['vehicle_id'];
$image = $newarray[$vehicle];
if ($image != 'placeholder')
{
echo '<div class="col-sm"><div class="card" style="width: 18rem;">
<h5 class="card-title text-center font-weight-bold">'.$year.' '.$make.' '.$model.'</h5>
<img class="card-img-top" src="'.$image.'" alt="'.$year.' '.$make.' '.$model.'">
<div class="card-body">
Edit
</div>
</div></div>';
}
else
{
if ($item['vehicle_type'] == 'atv') {
$image = '/new/images/vehicles/types/atv.png';
}
elseif ($item['vehicle_type'] == 'jeep') {
$image = '/new/images/vehicles/types/jeep.png';
}
elseif ($item['vehicle_type'] == 'motorcycle') {
$image = '/new/images/vehicles/types/motorchycle.png';
}
echo '<div class="col-sm"><div class="card" style="width: 18rem;">
<h5 class="card-title text-center font-weight-bold">'.$year.' '.$make.' '.$model.'</h5>
<img class="card-img-top" src="'.$image.'" alt="'.$year.' '.$make.' '.$model.'">
<div class="card-body">
Edit
</div>
</div></div>';
}
}
}
?>
</div>
</div>
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);
?>
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);
?>
i make index action in which i want to get data of calender and show this data using index.phtml but always no calendar shown,how i show calendar data?
here is my indexaction:
public function indexAction()
{
$dm = $this->getServiceLocator()->get('doctrine.documentmanager.odm_default');
$qb = $dm->createQueryBuilder('Calendar\Document\Calendar')->select('title', 'description');
$query = $qb->getQuery();
$calendars = $query->execute();
return array('calendars' => $calendars);
}
and here is my index.phtml:
<?php
$calendars = $this->calendars;
$title = 'Calendars by '.$this->escapeHtml($calendars[0]->email);
$this->headTitle($title);
?>
<h3><?php echo $this->escapeHtml($title); ?></h3>
<ul>
<li>Create New Calendar</li>
</ul>
<h4>Calendars created by you</h4>
<?php if (is_null($calendars)): ?>
<p>No calendars</p>
<?php else: ?>
<table class="table">
<tr>
<th>calendar name</th>
<th>description</th>
<th>owner</th>
<th>actions</th>
</tr>
<?php foreach ($calendars as $calendar) : ?>
<tr>
<td>
<a href="<?php echo $this->url('calendar',array('action'=>'show', 'id' => $calendar->calendar_id));?>">
<?php echo $this->escapeHtml($calendar->title);?>
</a>
</td>
<td><?php echo $this->escapeHtml($calendar->description);?></td>
<td>
<?php echo $this->gravatar($this->escapeHtml($calendar->email));?>
<?php echo $this->escapeHtml($calendar->email);?>
</td>
<td>
<a href="<?php echo $this->url('calendar',
array('action'=>'settings', 'id' => $calendar->calendar_id));?>">Settings</a>
<a href="<?php echo $this->url('calendar',
array('action'=>'delete', 'id' => $calendar->calendar_id));?>">delete</a>
</td>
</tr>
<?php endforeach; ?>
</table>
and here is my response:
Doctrine\ODM\MongoDB\Cursor Object
(
[baseCursor:Doctrine\ODM\MongoDB\Cursor:private] => Doctrine\MongoDB\Cursor Object
(
[connection:protected] => Doctrine\MongoDB\Connection Object
(
[mongo:protected] => MongoClient Object
(
[connected] => 1
[status] =>
[server:protected] =>
[persistent:protected] =>
)
[server:protected] => mongodb://127.0.0.1:27017/events
[options:protected] => Array
(
)
[config:protected] => Doctrine\ODM\MongoDB\Configuration Object
(
[attributes:protected] => Array
(
[mongoCmd] => $
[retryConnect] => 0
[retryQuery] => 0
[autoGenerateProxyClasses] => 1
[proxyDir] => data/DoctrineMongoODMModule/Proxy
[proxyNamespace] => DoctrineMongoODMModule\Proxy
[autoGenerateHydratorClasses] => 1
[hydratorDir] => data/DoctrineMongoODMModule/Hydrator
[hydratorNamespace] => DoctrineMongoODMModule\Hydrator
[defaultDB] => events
[metadataCacheImpl] => Doctrine\Common\Cache\ArrayCache Object
(
[data:Doctrine\Common\Cache\ArrayCache:private] => Array
how i show data on index page?
You need a view model to render your data. Instead of
return array('calendars' => $calendars);
You want this for a View:
$viewModel = new ViewModel
(
array
(
'calendars' => $calendars,
)
);
return $viewModel;
or this for Json:
$jsonModel = new JsonModel
(
array
(
'calendars' => $calendars,
)
);
return $jsonModel;
make sure to add the use statements for your controller:
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
If you want to specify a specific view you can use:
$viewModel->setTemplate('path/to/specific/view.phtml');
or
$viewModel->setTemplate('mapping/for/specifc/view');
with the mapping specified in your module config
Can you help me with my code. I am creating a super simple shopping cart that can add cart/update and remove. But as for now what I already did is the add to cart and the displaying of items. But I have an error. Everytime I refresh the page the session is automatically appending to the session array.
Now what I need to do is this.
Validate if the product is in the session list. If not create a session for that if yes just skip it.
And for the additional question. How can I create an update/remove function?
Here's my code so far. This process is only 1 PHP file.
$category = $_GET['cat'];
$product_id = $_GET['product'];
//fn_print_r($_SESSION);
//unset($_SESSION['cart']);
$product_detail = get_allproduct_detail($product_id);
$prod_price = $product_detail['prod_price'];
$sale_price = $product_detail['sale_price'];
$prod_type = $product_detail['prod_type'];
if(!empty($_POST['product_id']) && !empty($_POST['product_name']) && !empty($_POST['product_price']) && !empty($_POST['sale_price']) && !empty($_POST['qty'])) {
$sess_id = $_POST['product_id'];
$sess_name = $_POST['product_name'];
$sess_price = $_POST['product_price'];
$sess_sale_price = $_POST['sale_price'];
$sess_qty = $_POST['qty'];
$compute_total = $sess_sale_price * $sess_qty;
$cart_row = array(
'product_id' => $sess_id,
'product_name' => $sess_name,
'product_price' => $sess_price,
'sale_price' => $sess_sale_price,
'qty' => $sess_qty,
'total' => $compute_total
);
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
$_SESSION['cart'][] = $cart_row;
//fn_print_r($_SESSION);
}
Here's the form process
<form method="POST" action="?page=product&cat=<?php echo $_GET['cat']; ?>&product=<?php echo $_GET['product']; ?>" onsubmit="">
<div id="item_detail_right">
<label>Qty:<input type="text" name="qty" value="1" size="5" style="text-align: center" />
<input type="hidden" name="product_price" id="product_price" value="<?php echo $prod_price; ?>" />
<input type="hidden" name="sale_price" id="sale_price" value="<?php echo $sale_price; ?>" />
<input type="hidden" name="product_id" id="product_id" value="<?php echo $_GET['product']; ?>" />
<input type="hidden" name="product_name" id="product_name" value="<?php echo strtoupper(get_product_name($_GET['product'])); ?>" />
<input type="submit" value="+CART" />
<input type="button" value="+Wishlist" id="mywishlist" data-wishlist-id="<?php echo $_GET['product']; ?>" />
</div>
</form>
Here's the display of cart
if(!isset($_SESSION['cart']) || (count($_SESSION['cart']) == 0)) {
echo "<p>Your cart is empty</p>";
} else {
echo "<table border='0' style='font-size: 12px; width: 100%' cellpadding='5'>";
echo "<tr>";
echo "<td style='background-color: white; color: black; text-align: center'>Product ID</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Name</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Price</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Sale Price</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Quantity</td>";
echo "<td style='background-color: white; color: black; text-align: center'>Total</td>";
echo "<td style='background-color: white; color: black; text-align: center'></td>";
echo "</tr>";
$total = 0;
foreach($_SESSION['cart'] as $item) {
echo "<tr>";
echo "<td style='text-align: center; background-color: gray; color: black'>".$item['product_id']."</td>";
echo "<td style='text-align: left; background-color: gray; color: black'>".$item['product_name']."</td>";
echo "<td style='text-align: right; background-color: gray; color: black'>".number_format($item['product_price'],2)."</td>";
echo "<td style='text-align: right; background-color: gray; color: black'>".number_format($item['sale_price'],2)."</td>";
echo "<td style='text-align: center; background-color: gray; color: black'><input type='text' name='cart_qty[]' value='".$item['qty']."' size='10' style='text-align: center'></td>";
echo "<td style='text-align: right; background-color: gray; color: black'>".number_format($item['total'],2)."</td>";
echo "<td style='text-align: center; background-color: gray; color: black'><a href='#'>Update this?</a> | <a href='#'>Remove this?</div></td>"; //how can I use this to remove and update the session?
echo "</tr>";
$total += ($item['sale_price'] * $item['qty']);
}
echo "<tr>";
echo "<td colspan='7' style='text-align: right'>";
echo "<label>Subtotal Amount: </label><input type='text' name='subtotal' value='".number_format($total,2)."' readonly='readonly'>";
echo "<input type='submit' value='Place Item' />";
echo "</td>";
echo "</tr>";
echo "</table>";
}
Here's my sample output of array
Array
(
[visit] => nsrAROum86lb8VK
[slideshow] => 04-15-14
[cart] => Array
(
[0] => Array
(
[product_id] => 1
[product_name] => AJNA
[product_price] => 90
[sale_price] => 81
[qty] => 1
[total] => 81
)
[1] => Array
(
[product_id] => 1
[product_name] => AJNA
[product_price] => 90
[sale_price] => 81
[qty] => 1
[total] => 81
)
[2] => Array
(
[product_id] => 1
[product_name] => AJNA
[product_price] => 90
[sale_price] => 81
[qty] => 1
[total] => 81
)
[3] => Array
(
[product_id] => 1
[product_name] => AJNA
[product_price] => 90
[sale_price] => 81
[qty] => 1
[total] => 81
)
)
)
i uploaded my whole code to this link
http://www.mediafire.com/view/g6jah2bxbzda04l/aroma_shop.php
You can check wether the product is already in the cart.
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array();
}
// Instead of appending $cart_row immediately,
// $_SESSION['cart'][] = $cart_row;
// only add the $cart_row which has not been added previously
$found = false;
foreach ($_SESSION['cart'] as $c) {
if ($c['product_id'] == $cart_row['product_id']) {
$found = true;
}
}
if (!$found) {
$_SESSION['cart'][] = $cart_row;
}