php - 将 php 与 postgresql 链接
问题描述
我正在尝试使用 PHP 将数据从 javascript 发送到 Postgresql,但是我遇到了一个问题。我根本不知道我的 PHP 是否连接到 Postgres。我在数据库中没有任何错误或任何更改。
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");
};
和 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);
?>
解决方案
推荐阅读
- android - 在相对布局 Android 中适合大小
- android - 如何在Android Q(Android 10)上直接下载文件到下载目录
- ruby-on-rails - 如何在 ransack 的排序链接中使用自定义 url
- cmake - CMake vs vcpkg 三元组选择
- android - 如何在树莓派和安卓智能手机之间进行同步通信?
- node.js - InversifyJS 联合测试 sinon stub
- scala - 如何修复 Cinnamon 中出现的部分结果(Lightbend 遥测)
- c# - 应用程序自动重启后如何运行应用程序的一些方法和功能
- c# - 如何根据c#中的日期范围动态生成事件
- javascript - 反应:我是否应该将所有副作用逻辑放在 useEffect 中