This is fragment of my code:
<?php
session_start();
$_SESSION['counter']=0;
if(isset($_POST['id'])){
$id = $_POST['id'];
$id = strval($id);
@$_SESSION['order'] +=',';
@$_SESSION['order'] +=strval($id);
echo $_SESSION['order'];
$_SESSION['counter']+=1;
}
echo '<br>'.$_SESSION['counter'];
?>
and when I open up the page, I see this error
"Fatal error: Uncaught TypeError: Unsupported operand types: null +
string in C:xampphtdocspizzaindex.php:7 Stack trace: #0 {main}
thrown in C:xampphtdocspizzaindex.php on line 7"
Please help me repair this quickly, because I have to hand my project on until March 1st.
This code should import the data from $_POST['id']
to $id
and add this to $_SESSION['order']
with the ","
character. I tried to parse $id to string, but it seems like, it doesn’t work.
2
Answers
Adding a null value to a string value doesn’t work in php, so check the value of $_SESSION[‘order’] if it is null or not. And, += is used for arithmetic operations and not to concatenate
In this code, we first convert $_POST[‘id’] to a string using strval(). Then we check if $_SESSION[‘order’] exists and initialize it as an empty string if it doesn’t. We also add a comma separator only if $_SESSION[‘order’] is not empty. Then we concatenate $id to $_SESSION[‘order’] using the "." operator. Finally, we increment $_SESSION[‘counter’] and display it along with the updated $_SESSION[‘order’].
Note that it’s always a good practice to sanitize and validate user input to prevent security issues.