I have been trying to create a very simple shopping cart and I'm having a problem with my $_SESSION array. This is for a school project and I'm trying to make it as simple as possible.
The error I'm getting is:
Notice: Undefined index: cart in C:\xampp\htdocs\Final\menu.php on
line 31
Notice: Undefined offset: 5 in C:\xampp\htdocs\Final\menu.php on
line 31
if(isset($_GET['id'])){
$product_id = $_GET['id'];
$_SESSION['cart'][$product_id]++;
print_r($_SESSION);
print "<br>";
print_r($_GET);
}
Once I've added more than one item to a particular product_id, the error goes away. This is the way the tutorial I read explained to add items to the cart. Any suggestions?
Looks like $_SESSION['cart'] does not yet exist. Since it's going to be an array, instantiate it first with:
if(!array_key_exists('cart', $_SESSION)) $_SESSION['cart'] = array();
Since you have not yet assigned anything to $_SESSION['cart'][$product_id], you'll get this type of error when trying to increment it. You may want to try:
$_SESSION['cart'][$product_id] = (array_key_exists($product_id, $_SESSION['cart'])) ? $_SESSION['cart'][$product_id] +1 : 1;
or as an if statement:
if(array_key_exists($product_id, $_SESSION['cart'])) $_SESSION['cart'][$product_id]++;
else $_SESSION['cart'][$product_id] = 1;
When you do $_SESSION['cart'][$product_id]++; you are actually doing:
$_SESSION['cart'][$product_id] = $_SESSION['cart'][$product_id] + 1;
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ generates warning if they keys do not exist yet
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^ assigns without problems if they keys do not exist yet
The assignment with newly created keys is not the problem, the warning is generated by php trying to get the actual value of $_SESSION['cart'][$product_id].
To solve this you should properly initialize the variable:
$_SESSION['cart'][$product_id] = isset($_SESSION['cart'][$product_id])
? $_SESSION['cart'][$product_id]++
: 1;
Related
Warning: array_key_exists() expects parameter 2 to be array, string given in D:\xampp\htdocs\ecom\customer\data.php on line 45
Notice: Array to string conversion in D:\xampp\htdocs\ecom\customer\data.php on line 51
My Code
$qry = dbQuery("SELECT `orders_product`.`pd_id`, `op_quantity` FROM `orders_product`
INNER JOIN `products_detail` ON `products_detail`.`pd_id`=`orders_product`.`pd_id`
WHERE orders_product.order_id = $id");
if(dbNumRows($qry)>0) {
$cart="";
if(!isset($_SESSION['cart'])) { $_SESSION['cart']="";}
$result = dbFetchArray($qry);
while($result = dbFetchArray($qry)) {
$product_detail_id = $result["pd_id"];
$order_quantity = $result["op_quantity"];
// echo $product_detail_id;
#print_r($result);
if(array_key_exists($product_detail_id, $_SESSION['cart'])){
$quantity = $_SESSION['cart'][$product_detail_id]['quantity'] + $order_quantity;
$_SESSION['cart'][$product_detail_id]['quantity'] = $quantity;
} else {
$cart = array("pd_id"=>$product_detail_id, "quantity"=> $order_quantity);
$_SESSION['cart'][$product_detail_id] = $cart;
print_r($cart);
}
}
}
$return = 1;
echo json_encode($return);
}
First problem
Warning: array_key_exists() expects parameter 2 to be array, string given in D:\xampp\htdocs\ecom\customer\data.php on line 45
That's because you use $_SESSION['cart'] with function array_key_exists. So when a person enters the website for the first time the variable $_SESSION['cart'] is not set.
What you do then is assign an empty string.
if(!isset($_SESSION['cart'])) { $_SESSION['cart']="";}
So then you use empty string with function array_key_exists.
Solution
To resolve this issue simply change
if(!isset($_SESSION['cart'])) { $_SESSION['cart']="";}
to
if(!isset($_SESSION['cart'])) { $_SESSION['cart']=array();}
Second problem
Notice: Array to string conversion in D:\xampp\htdocs\ecom\customer\data.php on line 51
Now, this is only a notice so that's not a big issue. It may not even be something wrong. After you change to not display errors it won't affect your website in any way.
But why is this showing? Again the same reason as with the previous problem. You assign empty string to variable $_SESSION['cart'] but then you treat is as an array
$_SESSION['cart'][$product_detail_id] = $cart;
When you change the assignment from empty string to empty array this issue will be solved as well.
By the way when you write a one line if statement a good practice is not to use the braces
So I would write it like
$_SESSION['cart'] = isset($_SESSION['cart']) ? $_SESSION['cart'] : [];
Or even better
$_SESSION['cart'] = $_SESSION['cart'] ?? [];
But this is only php 7.0 and higher
I hope you understand now what was wrong and why. If you have any questions feel free to ask. I'll try to reply the best away I can.
Every time I try to run my code I am getting a 'Notice: Undefined offset: 1 Error
specifically coming from this line:
$acmark= $summary[1][1] += $student[$row][2] / 25;
I am new to PHP and would like to get this working with the least amount of changes possible. I have uploaded the full source code to Pastebin to make for easier viewing.
http://pastebin.com/Ur8u673V
Thanks in advance guys, Luke.
Looking at the code in your paste, you're initialising $summary to an empty array, and never actually adding anything to it before attempting to read the data. It's equivalent to:
$summary = array();
// ...
$acmark = $summary[1][1] += $student[$row][2] / 25; // $summary[1] isn't defined
Agree with George - you're initializing $summary as an array, but the offset starts at 0. Since you're incrementing in a loop, change line 140 to:
$acmark = $summary[][] += $student[$row][2] / 25;
That will eliminate the notice. You can apply the same solution to the other lines with undefined offsets as well to resolve the other notices.
Consider using an associative array(s) with foreach loops so the array keys are more meaningful. Associative arrays are easier to use and support the idea of using self-documenting code
i think u should set value of array first (maybe with 0), because if undefines is meaning that array is null value (null is different with 0)
add this code after $summary = array(); like below
$summary=array();
//additional code
for($sum=0; $sum<6; $sum++)
$summary[$sum][1]=0;
for($row=0; $row<25; $row++){
.
.
.
I'm looking for some help on calculating a total from lots of subtotals from a database, the code I'm using is working to calculate it, but the PHP echos an error saying that
Notice: Undefined variable: tot in ..............\viewing.php on line 192
But it is still calculating the total cost and echoing it, any ideas on how to get rid of that error?
I am getting the subtotals from a database using this:
while($row=mysql_fetch_array($result)) {
echo .....
$tot += $row['subtotal'];
}
At the bottom of the page, I've made it so it shows the total and its working, but its still giving me an error saying that the variable tot is undefined, any ideas?
It isn't an error, it's a notice!
Initialise
$tot = 0;
before your while loop
You need to define your $tot variable
Put this before using it in your loop
$tot = 0;
$tot = 0;
while($row=mysql_fetch_array($result)) {
echo .....
$tot += $row['subtotal'];
}
echo $tot;
From the php documentation:
It is not necessary to initialize variables in PHP however it is a
very good practice.
However it also says:
Relying on the default value of an uninitialized variable is
problematic in the case of including one file into another which uses
the same variable name. It is also a major security risk with
register_globals turned on. E_NOTICE level error is issued in case
of working with uninitialized variables..
You can turn off notices at a variable level by doing this:
while($row=mysql_fetch_array($result)) {
#$tot += $row['subtotal'];
}
Having said that best practice is:
$tot = 0;
while($row=mysql_fetch_array($result)) {
$tot += $row['subtotal'];
}
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 9 years ago.
I understand there are many posts on this issue. I have looked at the many many posts but for some reason I can seem to find an answer!
Any help will be very much appreciated. I am fairly new to PHP so I apologise if I say anything incorrectly.
I am trying to create a basic basket system using an array. I keep getting an error undefined index on line $_SESSION['cart'][$app_ID]++; The funny thing is it all functions correctly! I want to solve the error and not just turn off the error reporting.
if(isset($_GET['id'])){
$app_ID = $_GET['id']; //the item id from the URL
$action = $_GET['action']; //the action from the URL
$total = 0;
if (isset($app_ID)){
switch($action) {
case "add":
$_SESSION['cart'][$app_ID]++;
break;
case "remove":
$_SESSION['cart'][$app_ID]--;
if($_SESSION['cart'][$app_ID] == 0) unset($_SESSION['cart'][$app_ID]);
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
Thanks guys and gals.
You should use isset($_SESSION['cart'][$app_ID]) and maybe isset( $_SESSION['cart']) before, everywhere.
Generally you must make sure that and array index is present before referencing it. You can do this either with isset(), or writing code where that condition is inevitable (e.g. adding the index somewhere earlier).
The other part of your question, I suppose, is why your code works. The explanation is easy. When you reference a non-existent index, the notice you observed is emitted (in non-production environments) but that does not stop the program. Since there is nothing to be used, null is returned for that array value. So the value is assumed to be null, and ++ takes values, as integers, and null is converted to the integer 0, and then raised by one. Since ++ is an operator that writes, it will create the array item for you. Since $a++ is defined as $a=$a+1 it's easy to see that what you've written is $_SESSION['cart'][$app_ID]=$_SESSION['cart'][$app_ID]+1 which is in turn $_SESSION['cart'][$app_ID]=null+1 where null+1 is executed as 0+1 yielding 0, so 0 is assigned to (the formerly missing) array item. Hope this helps see clear. ;)
to use $_SESSION you must call session_start () first before send any header information
I hope this help you,
Cheers,
session_start(); // at the top
case "add":
if (isset( $_SESSION['cart'][$app_ID] )){
$_SESSION['cart'][$app_ID]++;
} else {
$_SESSION['cart'][$app_ID] = 1;
}
break;
It's worth to mention, that it's merely a Notice, not an error. You basically must check for array index existence and initialize it before referencing it.
if (isset($app_ID)) {
switch($action) {
case "add":
if (!isset($_SESSION['cart']) {
$_SESSION['cart'] = array();
}
if (!isset($_SESSION['cart'][$app_ID]) {
$_SESSION['cart'][$app_ID] = 0;
}
$_SESSION['cart'][$app_ID]++;
break;
case "remove":
if (isset($_SESSION['cart'] && isset($_SESSION['cart'][$app_ID]) {
$_SESSION['cart'][$app_ID]--;
if ($_SESSION['cart'][$app_ID] <= 0) {
unset($_SESSION['cart'][$app_ID]);
}
}
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
}
I've also changed == 0 in remove to <= 0 just to be safe.
How can I check for a offset in cake php in a loop?, I have a message saying this...
Notice (8): Undefined offset: 1 [APP\views\cars\car_details.ctp, line 53]
Notice (8): Undefined offset: 2 [APP\views\cars\car_details.ctp, line 53]
Its in a foreach loop and retrieving items like this
$car_ratings['CarRating'][$j]['reccar_num']
Just run a check of array_key_exists() on the element like:
if(array_key_exists($j, $car_ratings['CarRating'])){
// true
}
Check the size of the array (using count()) then don't go over it.
For example:
for ($i = 0; $i < count($car_ratings['CarRating']); ++$i) {
// use the array at $i
}
Alternatively if you don't want to modify the loop, you can use array_key_exists() to determine if the array has a value defined for a particular key.
Of course using foreach would be better here.
If you could provide more context this answer might be better.