-1

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:\xampp\htdocs\pizza\index.php:7 Stack trace: #0 {main} thrown in C:\xampp\htdocs\pizza\index.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.

Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • 3
    Concatenation in php is done with `.` – u_mulder Feb 22 '23 at 19:32
  • 2
    [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](https://meta.stackoverflow.com/questions/326569/under-what-circumstances-may-i-add-urgent-or-other-similar-phrases-to-my-quest). See also [ask] – ADyson Feb 22 '23 at 19:50

2 Answers2

0

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

Ayb009
  • 220
  • 2
  • 11
0
session_start();
$_SESSION['counter'] = 0;

if(isset($_POST['id'])) {
    $id = strval($_POST['id']);
    if(!isset($_SESSION['order'])) {
        $_SESSION['order'] = '';
    }
    if($_SESSION['order'] != '') {
        $_SESSION['order'] .= ',';
    }
    $_SESSION['order'] .= $id;
    echo $_SESSION['order'];
    $_SESSION['counter'] += 1;
}
echo '<br>' . $_SESSION['counter'];

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.