0

I'm trying to figure out the best way to find a combination of values in a json array and if it exists, return an error message. If the combination of values is not present in the array, post them to the server. Here is what I have so far.

JSON

[{
  "username": "[email protected]",
  "contest": "TV",
  "timestamp": "Fri Nov 09 2018 16:33:38 GMT-0500 (Eastern Standard Time)"
}, {
  "username": "[email protected]",
  "contest": "Phone",
  "timestamp": "Fri Nov 09 2018 18:33:51 GMT-0500 (Eastern Standard Time)"
}]

I'm using ajax to post the details to php and that part works well.

        $.ajax({
            type: 'POST',
            url: 'update.php',
            data: { theuser: theuser, thecontest: thecontest, timestamp: timestamp },
            success: function() {
                //Show confirm notification hide btns and close the modal
                $('.modalbtns').hide();
                $('#successbox').fadeIn();
                setTimeout(function() {
                    $('#ModalCenter').modal('hide')
                }, 2400);
            },
            error: function() {
                // do something on error
            }
        });

This is what I have so far for the php (update.php)

<?php

$theuser = $_POST['theuser'];
$thecontest = $_POST['thecontest'];
$timestamp = $_POST['timestamp'];

if (is_writable('alldata.json')) {

    $json = file_get_contents('alldata.json');
    $data = json_decode($json);
    $data[] = array('username'=> $theuser, 'contest' => $thecontest, 'timestamp' => $timestamp);
    file_put_contents('alldata.json', json_encode($data));

} else {
    //echo "file is not writable, check permissions";
}

?>

For example what I'm trying to achieve is

Before posting, check in the json array if the following combination exists. username = [email protected] AND contest = Phone If it exists, return a custom message to the page e.g. (you already registered). If the combination is not in the json array, post to the file.

I believe it has to be something in the lines of

foreach($data as $item)
{
    if($item->username == $username) || ($item->contest == $contest){
        //combination found, do not post!
    }
}

But I can't get it to work, thanks for the help!

1
  • Where is the if($item->username == $username) || ($item->contest == $contest){? This sounds like a DB would be easier to use and manage as well. Commented Nov 12, 2018 at 17:05

2 Answers 2

1

You have to change the backend PHP code in the following way,

<?php
    $theuser = $_POST['theuser'];
    $thecontest = $_POST['thecontest'];
    $timestamp = $_POST['timestamp'];

    if (is_writable('alldata.json')) {
        $json = file_get_contents('alldata.json');
        $data = json_decode($json, true);
        $flag = false;
        foreach($data as $d){
            if($d['username'] == $theuser && $d['contest'] == $thecontest){
                $flag = true;
                break;
            }
        }
        if(!$flag){
            $data[] = array('username'=> $theuser, 'contest' => $thecontest, 'timestamp' => $timestamp);
            file_put_contents('alldata.json', json_encode($data));
        }else{
            // echo "you are already registered for the contest";
        }
    } else {
        // echo "file is not writable, check permissions";
    }
?>

Summary of needed changes:

  • Pass an additional argument true to json_decode() function to convert returned objects into associative arrays.
  • Assuming that a user can register for multiple contests, you should use && condition instead of || to check whether the user is already registered for a particular contest or not.
  • Use a boolean flag $flag and foreach loop to check if the user is already registered, display a simple message if already registered or attach the user data to json string if not registered.
Sign up to request clarification or add additional context in comments.

2 Comments

thanks, it works! How can I send the "you are already registered" string back to ajax?
@Carlos27, Your success callback function of AJAX would look something like this, success: function(data){alert(data);} where data is the returned data from server i.e. your echo statement.
0

You can simply create a function to do that check and use your loop code:

<?php
function check_combination($data){
    foreach($data as $item)
    {
        if($item->username == $username) || ($item->contest == $contest){
            return false; //if match found function will return by breaking the loop.
        }
    }
    return true; //it will be returned after all the values are iterated.
}


check_combination($data);

But please note if your data is too big this can be a performance issue, a better approach will be required.

1 Comment

You are right, I noticed that after getting close to 1000 entries (3 fields per entry) I got the following error in php.. [10-Dec-2018 14:42:21 UTC] PHP Warning: Invalid argument supplied for foreach() in /home/username/public_html/calendrier/update.php on line 10 And my json file got completely wiped. Is that really enough to create an issue with php? What do you suggest as a better approach?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.