Retrieve data from the following fields: {"attending":0,"eventid":1,"userid":1} using PHP

After receiving an array from JAVA and using print_r($_POST), I have tried various methods to extract data but with no success. The format of the array is as follows:

{"attending":0,"eventid":1,"userid":1}

I've attempted different approaches found on SO and online, such as those surrounded by single quotes (' ') and square brackets ([]).

This is my code snippet:

print_r($_POST);
$data = json_decode($_POST);

$userid = $data['userid'];
$eventid = $data['eventid'];
$attending = $data['attending'];

My question is, how can I effectively retrieve values from the Post method and assign them accordingly?

I'm still new to PHP, so please be patient with me.

I also gave this a shot:

$data = json_decode($_POST, true);

But now I'm encountering the following warning:

Warning: json_decode() expects parameter 1 to be string, array given in C:\xampp\htdocs\attendanceradio.php on line 9

Here's the output of var_dump($_POST);:

Array
                                                          (
                                                              [{"attending":0,"eventid":2,"userid":1}] => 
                                                          )
                                                          array(1) {
                                                            ["{"attending":0,"eventid":2,"userid":1}"]=>
                                                            string(0) ""
                                                          }

And here is the complete PHP code:

<?php

    $user = 'root';
    $pass = '';
    $db = 'testuser';

    $con=mysqli_connect('localhost', $user, $pass, $db) or die('Unable to connect');
    print_r($_POST['json']);
    var_dump($_POST);

    $json = json_decode(trim(key($_POST), '[]'), true);
        var_dump($json);
    $userid = $json['userid'];
    $eventid = $json['eventid'];
    $attending = $json['attending'];

    $statement = mysqli_prepare($con, 
    'INSERT INTO user_has_event(user_user_id, event_event_id, attendance)
        VALUES (?, ?, ?)
        ON DUPLICATE KEY UPDATE attendance = ?');

    mysqli_stmt_bind_param($statement, 'iii', $userid, $eventid, $attending);
    mysqli_stmt_execute($statement);

    mysqli_stmt_store_result($statement);
    mysqli_stmt_bind_result($statement, $userid, $eventid, $attending);

    mysqli_stmt_close($statement);

    mysqli_close($con);
?>

Answer ā„–1

According to the information you provided, a solution similar to this might be effective:

<?php

$data = json_decode(trim(key($_POST), '[]'), true);

var_dump($data);

?>

Answer ā„–2

An issue arose when an Array was unexpectedly passed instead of a string, as revealed by the var_dump result showing POST returning an array.

To properly decode the JSON string, the code must indicate the array index where the string can be found. The corrected code snippet is as follows:

$data = json_decode($_POST[0], true);

$userid = $data['userid'];
$eventid = $data['eventid'];
$attending = $data['attending'];

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Yii: the sequel to the query parameter

I am attempting to query my database in Yii framework. $query = Task::find() ->where([Task::tableName().'.parent_id' => 0]); $query->leftJoin(TaskModel::tableName(), [TaskModel::tableName().'.task_id' => Task::table ...

What is the best way to display the output after retrieving an array?

Database : --> product table P_id P_name P_uploadKey 1 Cemera 7365 2 Notebook 7222 3 Monitor 7355 4 Printer 7242 --> buy table B_id P_id B_nam ...

Challenges with regular expressions (preg_match)

Apologies if this question has already been asked, but I'm having trouble finding a clear answer online today! I'm trying to validate a form field and ensure that it contains exactly 3 uppercase letters, no more and no less. My various attempts ...

Discovering how to retrieve data from the payload() function when receiving information from Firestore using an Arduino

Utilizing Arduino to access data from Firestore, a database, has been successful. By using the REST API, I managed to retrieve the payload from Firestore. However, my goal now is to store some of this data into a boolean variable. Here is the information ...

Creating geometric designs on an image and storing them using PHP

I am attempting to retrieve an image from a specific location on my server, draw lines on it, and then save the modified image back to the same location. Below is the code I am using: function drawShapes($src_path, $json) { echo "---inside dra ...

Limitations on Embedding Videos with YouTube Data API

I have been using the Youtube Data API to search for videos, but I am encountering an issue with restricted content appearing in the results. Specifically, music videos from Vevo are showing up even though I only want videos that can be embedded or placed ...

Storing user input values in a database using PHP

How can I efficiently calculate the sum of values from multiple input files and then store them in a database for later use? Here are examples of my input fields: <input type="checkbox" name="test[]" value="1"> <input type="checkbox" name="test[ ...

Automatically redirecting to the designated page once the radio button option is submitted

I am encountering an issue with my form. I require it to redirect the user to different pages based on the selection of a radio button. The user must choose one of two options and click "next," and depending on their choice, they should be redirected to an ...

"The art of sending Ajax requests in combination with the powerful Code Ign

Struggling to send 2 values to my codeigniter controller has left me feeling defeated. Despite numerous attempts, I have been unsuccessful. The Controller requires the following inputs: $token = $this->input->post('cc_token'); $hash = $th ...

Troubleshooting Problems with JSON Parsing in Node.js

After retrieving a JSON file and utilizing NodeJS to parse it, the structure of the JSON file appears as follows: { "id": 5, "x": 9.996, "y": 0.135, "v": { "x1": 0.653, "y1": -0.064 }, "z": 1.4730991609821347 }, { ...

What is the process for utilizing jQuery and ajax to retrieve data from a MySQL database?

I am currently working on a form that includes a "select" box. The goal is to display the relevant records from the database on the same page once an option is selected. This process involves two files: an HTML page containing the form: <form id="theF ...

Is it possible to seamlessly alternate between JSON using the Jackson processor and XML using XStream, or is it feasible to use both formats simultaneously

I am in the process of developing a Web Server that can convert an Object into both JSON and XML formats. I have successfully used Jackson to serialize an object into JSON through my REST Interface, but I also need to support XML serialization. Recently, ...

Are you seeking assistance with documentation for PHP projects, whether they be large or small

At this moment, the topic of documentation for programmers is a major conversation point. How do you approach this aspect? When introducing a new team member to a "large" PHP project, what is the most effective method? What essential resources does a newc ...

Converting std::list to JSON using Boost Property Tree

After struggling with this problem for the past few days, I am still unable to figure it out. I have a std::list container that I need to serialize into a JSON string in order to send it over the network. NOTE: This is how I compile my code: g++ -std=c++ ...

Attempting to retrieve JSON data and present it in a grid layout

I have a JSON file with the following data: { "rooms":[ { "id": "1", "name": "living", "Description": "The living room", "backgroundpath":"https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSrsU8tuZWySrSuRYdz7 ...

Exploring BigQuery Audit Logs - identifying JSON metadata keys containing the '@' sign

When crafting queries in Log Explorer, we have the option to utilize the following syntax: protoPayload.metadata."@type"="type.googleapis.com/google.cloud.audit.BigQueryAuditMetadata" After successfully setting up a sink to store all l ...

Having trouble running a form due to the inclusion of JavaScript within PHP code

My PHP code includes a form that connects to a database, but when I add JavaScript to the same file, the form does not execute properly. (I have omitted the insert code here.) echo '<form action="$_SERVER["REQUEST_URI"];" method="POST">'; ...

Exploring the inner workings of a JSON with Ajax and PHP

I'm working on a project that involves a JSON file called items.json. My goal is to create a search box where users can input either the name of an item or its category, and see live search results as they type. Here's what Iā€™m aiming for: If ...

Is it worth converting XML to JSON for better performance levels?

Currently, I am storing my settings using the Visual Studio integrated Settings-Management-System, which utilizes XML. However, in a recent article on fastJSON (http://www.codeproject.com/Articles/159450/fastJSON), I learned that "the fastest XML is ~50x ...

ListView Adapter fails to display Android TimeStamp values

Whenever my ListView refreshes or reloads, the timestamp is consistently showing as Jan 17, 1970. Why does this keep happening? The value of my timestamp 1441339200 = 2015-09-04 Snippet of code for the timestamp CharSequence timeAgo = DateUtils ...