首页 > 解决方案 > 将 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);
?>

数据库

标签: phppostgresql

解决方案


推荐阅读