This isn't as hard as you think, but you will have to make sure the exposed back-end is safe and sane in PHP. The interface could look something like this :
function dataHandler(Variable,Value,ID){
var Data = new FormData();
Data.append('ID', ID);
Data.append('Value', Value);
Data.append('Variable', Variable);
var DBIO = new XMLHttpRequest();
DBIO.onreadystatechange = function() {
if (DBIO.readyState == 4) {
parseData(DBIO.responseText);
}
DBIO.open('POST', './DBIO.php', true);
DBIO.send(Data);
}
Display More
On the PHP side, you have a number of options, but it is important to make sure that it is secure because this interface is exposed to the world. There are plenty examples on how to do this properly, but essentially, you have to make sure that the PHP script isn't able to access and read/write in places where it shouldn't.
DBIO.php can be build to both read and write from a database. In case of a non-null value and no ID, you could make it insert, With an ID and a value, do an update and with a ID and a null value, do a select.
For returning data, you could simply return a string and parse it in JS. I tend to generate XML and return that for parsing, but that is a personal preference.
A basic setup would look something like this. You can find most code snippets you need easily online.
<?php
$ID = $_POST['ID'];
$variable = $_POST['variable'];
$value = $_POST['value'];
/*
code to make sure the variable is valid to use (an array or something) and code to clean up the data for injection prevention..
*/
/*
database connection code
*/
if (trim($ID) == "" ){
// build a insert query
$DBIOResult = 'INSERT';
} else if (trim($ID) != "" AND trim($value != "") ){
// build a update query
$DBIOResult = 'UPDATE';
} else if (trim($ID) != "" AND trim($value == "") ){
// build a select query
$DBIOResult = 'SELECT';
}
/*
code to execute query
*/
?>
<?xml version="1.0" encoding="UTF-8"?>
<DBIO>
<DBIOResult><?php echo $DBIOResult?></DBIOResult>
<ID><?php echo $ID?></ID>
<variable><?php echo $key?></variable>
<value><?php echo $value?></value>
</DBIO>
Display More
You can make this as simple or complex as you like, but the important part is the security of the interface. I'd advice to follow these instruction for the DBIO : https://phpdelusions.net/pdo