I have built a tool which collects data. The data should be separated to id, dropzone and item. Which is basically a sorting cards tool.
I have built a function that collects data, which looks like this in the end. See picture:
Now I want to send this to PHP, while searching1()
is the data collecting function.
function sendData() {
let target = 'php/data.php';
let data = searching1();
JSON.stringify(data);
let sendData = function () {
$.post('php/data.php', {
data: data
}, function (response) {
});
};
fetch(target, {
method: "POST",
mode: "same-origin",
credentials: "same-origin",
headers: {
'Content-Type': 'application/json',
//'Accept': 'application/json',
},
body: JSON.stringify({
data
})
}).then(res => {
const response = res.json();
console.log(data);
return response;
});
My problem now is that the data is arriving in PHP, but I need separate now I guess from each other, cause now everything is one big array. Is there any smart function to do this? I've tried something like:
$data = $decoded ['data'];
$dropzone = $decoded['data'];
$item = $decoded ['data'];
$id = $decoded ['data'];
But this doesn't quite work, because I get the "Array to string conversion" notice.
So basically the question is, can I transform this one big array into strings (right?), to insert it into an SQL database?
if ($contentType === "application/json") {
$content = trim(file_get_contents("php://input"));
$decoded = json_decode($content, true);
$data = $decoded ['data'];
$dropzone = $decoded['data'];
$item = $decoded ['data'];
$id = $decoded ['data'];
$create_table = "CREATE TABLE IF NOT EXISTS test (id VARCHAR(255), dropzone VARCHAR(255),item VARCHAR(255))";
$table_statement = $pdo->exec($create_table);
if (is_array($data) || is_object($data)) {
foreach ($data as $value) {
$sql = "INSERT INTO test (id, dropzone, item) VALUES ('$id','$dropzone','$item')";
$stmt = $pdo->exec($sql);
}
if (is_array($decoded)) {
$response = $decoded;
header('Content-Type: application/json');
echo json_encode($response);
} else {
echo("FEHLER");
}
}
}
This is basically my PHP code. I have the database config and database connect already done.
I'm super happy for any help..