I am trying to send the data from javascript to Postgresql using PHP however I am facing a problem. I don't know if my PHP connects to the Postgres at all. I get no errors or any changes in the database.
js function
function sendData(Firstname, Surname, Age) {
const hr = new XMLHttpRequest();
const url = "post.php";
const data = "Firstname=" + Firstname + "&Surname=" + Surname + "&Age=" + Age;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Send the data to PHP now... and wait for response to update the status div
hr.send(data); // Actually execute the request
}
window.onload = function () {
sendData("rob", "roy", "23");
};
and post.php
<?php
$First = pg_escape_string($_POST['Firstname']);
$Last = pg_escape_string($_POST['Surname']);
$Age = pg_escape_string($_POST['Age']);
$host = "host = localhost";
$port = "port = 5432";
$dbname = "dbname = postgres";
$credentials = "user = postgres password=root";
// Connecting, selecting database
$dbconn = pg_connect("$host $port $dbname $credentials")
if($dbconn){
echo "Connected";
}
else{
die('Could not connect: ' . pg_last_error());
}
//tried only people doesn't work
$dbquery = "INSERT INTO public.people(Firstname, Surname, Age) VALUES('$First','$Last','$Age')";
$result = pg_query($dbconn, $dbquery);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
echo "Operation done successfully\n";
// Closing connection
pg_close($dbconn);
?>