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!
if($item->username == $username) || ($item->contest == $contest){? This sounds like a DB would be easier to use and manage as well.