Im getting an undefined offset error. I know why i am getting the error and where it is. What i am trying to work out is how to implement the appropriate error checking to prevent this from happening. The method is currently being called via ajax and thus the error cause's issues with the return of any strings etc.
Following is the class's method being called, its variables are being set vie $_GET.
$id = $_GET['id'];
$product = $_GET['name'];
$price = $_GET['price'];
//check for existing product
for($i = 0; $i <= count($_SESSION['BASKET']); $i++) {
//if product exsits incrent by 1
if($_SESSION['BASKET'][$i]['id'] == $id){
$_SESSION['BASKET'][$i]['amount'] = $_SESSION['BASKET'][$i]['amount'] + 1;
break;
//if doesnt exsist creat product array
} else {
$item = array('id' => $id,'amount' => 1,'product' => $product,'price' => $price);
}
}
if(isset($item)){
//push product to session array
array_push($_SESSION['BASKET'], $item);
}
As you can see the method checks to see if the basket currently contains a product and updates by incrementing the quantity ('amount'). I have a constructer that creates the basket array in the class. The issue occurs when the $_SESSION['BASKET'] is called and is empty but still exists as in :
array (
)
this creates and undefined offset error when checking the id in the if statement as the array technically exists but the offset 0 does not. Any ideas how i can handle this?.
Code changes i a have made that cause the same error
if(isset($_SESSION['BASKET'][$i]) && $_SESSION['BASKET'][$i]['id'] == $id){
I have moved the logic outside the loop and added a bool variable, i can then query this to check if a item was found in the array. This allowed me to create another if statement to check if the sessions values were set rather than checking if the array was created.
$id = $_GET['id'];
$product = $_GET['name'];
$price = $_GET['price'];
$exsist = false;
//check for existing product
for($i = 0; $i <= count($_SESSION['BASKET']); $i++) {
if(isset($_SESSION['BASKET'][$i])){
//if product exsits incrent by 1
if(isset($_SESSION['BASKET'][$i]) && $_SESSION['BASKET'][$i]['id'] == $id){
$_SESSION['BASKET'][$i]['amount'] = $_SESSION['BASKET'][$i]['amount'] + 1;
$exsist = true;
break;
}
}
}
if($exsist != true){
$item = array('id' => $id,'amount' => 1,'product' => $product,'price' => $price);
array_push($_SESSION['BASKET'], $item);
}
Related
I have a multidimensional array. The parent array includes items that each item inside is an array with its properties.
insertProduct.php checks everytime I add a new product to the array if the product already exists. If it doesn't it pushes it to the array, if it already exists it finds it and adds +1 to its quantity.
I am trying to create a functionality where pressing a button "Undo" removes the latest addition whether it was a whole product (which means its QTY would be 1 so it removes it altoghether) or if the latest addition was just a QTY increase (from 1 to 2) then remove 1 from the QTY.
However my issue is when I add a product that already exists but is not in the last spot of the array, the QTY does increase as it should be but then the UNDO does not do -1 to this item's QTY.
I don't know if it's alright to post a video but here's the pattern of the problem in a short gif
insertProduct.php
if (isset($_SESSION['myArray'])) {
$inserted_products = $_SESSION['myArray'];
$position = array_search($inserted_product_ean, array_column($inserted_products,0));
//check if new product already exists
if ($position !== false) {
$inserted_products[$position][2] = $inserted_products[$position][2] + 1;
$latest_product = $inserted_products[$position];
$_SESSION['latestProduct'] = $latest_product;
$_SESSION['myArray'] = $inserted_products;
} else {
array_push($inserted_products, $product); //$product is an array of info about the item inserted
$latest_product = $product;
$_SESSION['latestProduct'] = $latest_product;
$_SESSION['myArray'] = $inserted_products;
}
} else {
$latest_product = $product;
$_SESSION['latestProduct'] = $latest_product;
array_push($inserted_products, $product);
$_SESSION['myArray'] = $inserted_products;
}
deleteLastEntry.php
<?php
if (isset($_SESSION['myArray'])) {
$inserted_products = $_SESSION['myArray'];
$inserted_products_length = count($inserted_products);
if ($inserted_products_length > 0){
$latest_product = $_SESSION['latestProduct'];
$qty = $latest_product[2];
if ($qty !== false && $qty > 1) {
$qty = $qty - 1;
$latest_product[2] = $qty;
array_pop($inserted_products);
array_push($inserted_products, $latest_product);
$_SESSION['myArray'] = $inserted_products;
}else{
array_pop($inserted_products);
$_SESSION['myArray'] = $inserted_products;
}
}else{
echo '<div class="error-msg">No products to remove</div>';
}
}
?>
I'm trying to make a profile completion progress, which shows the percentage of how much a user has completed his profile settings. If a user has filled in a field, he receives +15 or +5, however, if the field is not filled in he receives +0.
the code I did is really bad, with variable repetitions, I wanted to know if you knew a cleaner way to do this.
if (!empty($user->avatar)) {
$avatar = 15;
} else { $avatar = 0; }
if (!empty($user->copertina)) {
$copertina = 15;
} else { $copertina = 0; }
// dati personali
if (!empty($user->name)) {
$name= 5;
} else { $name = 0; }
if (!empty($user->last_name)) {
$last_name = 5;
} else { $last_name = 0; }
[...]
if (!empty($user->biografia)) {
$biografia = 5;
} else { $biografia = 0; }
$personal = $avatar+$copertina+$name+$last_name+$sesso+$nascita;
$gaming = $steam+$battlenet+$xbox+$playstation+$switch+$uplay+$origin+$ds;
$social = $twitter+$facebook+$biografia;
$punti = $personal+$gaming+$social;
how do I remove all the others {$ variable = 0}?
You can't really, since you want the value to be a number, and not "undefined". You could initialize your variables to 0 like in this answer stackoverflow.com/questions/9651793/….
If you want to get into type comparisons for null variables, check php.net/types.comparisons. I would just initialize the variables to 0 and remove all the else.
OR...
modify your $user object to have all these variables in an array ($key:$value). You can then initialize the array to 0 all over, and modify it. Adding a new profile value would be easy, and adding array values is quick.
This snippet :
if (!empty($user->avatar)) {
$avatar = 15;
}
else {
$avatar = 0;
}
is semantically equivalent to :
$avatar = (bool)$user->avatar * 15;
Explanation:
Non-empty field gets converted to true and empty string or null gets converted to false
Because we do multiplication php true/false values gets converted to 1/0
So after multiplication you get 15 * 1 or 15 * 0 - depending if your field was used or not.
Already read some of questions about this problem on stackoverflow and none of that answers apply to me.
When I run:
$item_price = ItemPrice::where('item_name',$itemname)->first();
and then
$item_price->price
I get Trying to get property of non-object but when I run:
dd($item_price = ItemPrice::where('item_name',$itemname)->first());
It's returning object with attributes name, price etc. I don't really understand what is happening here.
Full code:
foreach ($inventorydecoded->assets as $asset) {
$i = 0;
$a = 0;
while ($a < 1) {
if ($inventorydecoded->descriptions[$i]->classid == $asset->classid) {
$a = 1;
$classid = $inventorydecoded->descriptions[$i]->classid;
$itemname = $inventorydecoded->descriptions[$i]->market_hash_name;
$tradable = $inventorydecoded->descriptions[$i]->tradable;
$name_color = $inventorydecoded->descriptions[$i]->name_color;
;
}
$i++;
} // end of while
if ($tradable === 1 && strpos_arr($itemname, $blacklist) == false ) {
$item_price = ItemPrice::whereItemName($itemname)->first();
// dd(ItemPrice::where('item_name',$itemname)->first());
$items[] = ['assetid' => $asset->assetid,'classid'=> $classid,'itemname'=>$itemname,'name_color'=>$name_color,'price'=> $item_price->price];
$serialized_inventory = serialize($items);
}
} // end of foreach
You're using this query in loop, so one of those is empty and returns null. So you need to do simple check:
if (is_null($item_price)) {
// There is no price for this item, do something.
}
Try this:
$item_price = ItemPrice::whereItemName($itemname)->first();
I'm calling in data from a JSON file. One of my elements is:
"mainImg_select":""
Sometimes this has a value, sometimes it won't - in this case it's empty. I put this (as well as other) variables in an object called Product.
When trying to set $product -> mainImg, I'm trying to see whether the JSON value is empty or not. If it's empty, I want to get the first value of another set of images, $more_imgsand make that the main image. Here's my code:
if(!is_null($mainImg)) {
$product->mainImage = $html->find($mainImg, 0)->src;
for ($idx = 0; $idx < 10; $idx++) {
$more = $html->find($more_imgs, $idx);
if (!is_null($more)) {
$product->moreImages[$idx] = $more->src;
} else {
return;
}
}
} else {
for ($idx = 0; $idx < 10; $idx++) {
$more = $html->find($more_imgs, $idx);
if (($idx == 0) && (!is_null($more))) {
$product->mainImage = $more->src;
} elseif (!is_null($more)) {
$product->moreImages[$idx] = $more->src;
} else {
return;
}
}
}
When I run the code, I get Notice: Trying to get property of non-object in relation to $product->mainImage = $html->find($mainImg, 0)->src;
I assume this has something to do with the if(!is_null($mainImg)) above it, because $mainImg SHOULD be null as defined in the JSON. If not, what's the best thing to use here?
EDIT: Here's some more detailed code for when the Product object is being set:
http://pastebin.com/EEUgpwgn
You should change !is_null to !empty as is_null() will return false even if "mainImg_select" is equal to empty string "".
Whether the $mainImg isn't found on your HTML; the code $html->find($mainImg, 0) will return null and then you will attempt to access the src parameter of a null object.
( from the Documentation of the php simple HTML Parser Library :
// Find (N)th anchor, returns element object or null if not found (zero based)
$ret = $html->find('a', 0);
)
You have to do this:
if (null !== ($img = $html->find($mainImg, 0))) {
$imgSrc = $img->src; // Here the HTML Element exists and you can access to the src parameter
}
I am trying to create logic to see what checkbox is selected (of 5 possible checkboxes) and if it is selected assign it a value of 0. if it is not selected I was to assign it a value of 1. The proceeding code snippet highlight this but throws a parse error in my else statement and I cannot fighure out why.
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = 'unchecked';
$chkBox2 = 'unchecked';
$chkBox3 = 'unchecked';
$chkBox4 = 'unchecked';
$chkBox5 = 'unchecked';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
else{
$chkBox1 = '1';
}
}//End of chkBox1Selected logic
You don't understand how checkboxes work. If a checkbox is deselected before posting, it will not be set on post.
Therefore, the only condition that will ever be present in your code is that every value will show as 1, since they cannot be overridden.
Take this snippet and try it out. It dynamically loops for the amount of variables you need and assigns the values based upon the submitted value.
$_POST['chkBox4'] = 'test';
for( $i = 1; $i <= 5; $i++ )
{
$name = 'chkBox' . $i;
$$name = !isset( $_POST[$name] ) ? 0 : $_POST[$name];
}
print $chkBox2 . ' // '. $chkBox4;
http://codepad.org/51RotnCf
Ok I got it to work from a syntax standpoint, however now no matter what is selected it is still assigning a value of 1 to all the checkboxes and not changing the selected checkbox to a value of 0. Here is the new code that is correct from a syntax standpoint but defaults to 1 no matter what:
//Check to see what checkbox is marked for correct answer
//Correct answer variables
$chkBox1 = '1';
$chkBox2 = '1';
$chkBox3 = '1';
$chkBox4 = '1';
$chkBox5 = '1';
if (isset($_POST['chkBox1'])) {
if ($chkBox1 == 'chkBox1Selected') {
$chkBox1 = '0';
}
}//End of chkBox1Selected logic
if (isset($_POST['chkBox2'])) {
if ($chkBox2 == 'chkBox2Selected') {
$chkBox2 = '0';
}
}//End of chkBox2Selected logic
if (isset($_POST['chkBox3'])) {
if ($chkBox3 == 'chkBox3Selected') {
$chkBox3 = '0';
}
}//End of chkBox3Selected logic
if (isset($_POST['chkBox4'])) {
if ($chkBox4 == 'chkBox4Selected') {
$chkBox4 = '0';
}
}//End of chkBox4Selected logic
if (isset($_POST['chkBox5'])) {
if ($chkBox5 == 'chkBox5Selected') {
$chkBox5 = '0';
}
}//End of chkBox5Selected logic