I need to fetch some data from a mysql database. For that I created get_data.php on the server and a js function to retrieve that data on the client. Is this the proper way to do it? What would you change?
get_data.php
<?php
require_once('database.php');
header("Access-Control-Allow-Origin: *");
if ($_SERVER['REQUEST_METHOD'] != 'POST' || !isset($_POST['entryID'])){
exit('Bad request data');
}
$db = db_connect();
$stmt = $db->prepare("SELECT `data` FROM `entries` WHERE `id` = ? LIMIT 1;");
$stmt->bind_param('i', $_POST['entryID']);
$stmt->execute();
$res = $stmt->get_result();
$stmt->close();
if ($res->num_rows > 0){
$arr = $res->fetch_assoc();
$json = array('status'=> 1, 'data'=>$arr['data']);
}else{
$json = array('status'=> 0);
}
echo json_encode($json);
?>
Code to fetch that data in javascript:
function getRemoteData(entryID) {
const defaultErrorMessage = '## This page isn\'t ready (yet)';
const form = new FormData();
form.append('entryID', entryID);
const d = fetch(requestUrl + '/get_data.php',
{
method: 'POST',
body: form,
})
.then(response => response.json())
.then(json => {
if (json.status == 1 && json.data != "")
return gunzipString(json.data);
return defaultErrorMessage;
});
return d;
}
It works fine but I'm not sure I'm doing things properly.