卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章79305本站已运行4413

PHP 函数如何使用 PostgreSQL 调用外部函数?

如何使用 php 调用 postgresql 外部函数?创建外部函数,例如使用 c 或 perl。使用 create function 语句将外部函数加载到 postgresql。通过 pg_query() 函数在 php 中调用外部函数。

PHP 函数如何使用 PostgreSQL 调用外部函数?

如何使用 PHP 函数调用 PostgreSQL 外部函数

前言

PostgreSQL 提供了创建外部函数的功能,允许您调用其他编程语言中编写的函数。PHP 是最流行的 Web 开发语言之一,因此了解如何使用 PHP 调用 PostgreSQL 外部函数至关重要。

立即学习“PHP免费学习笔记(深入)”;

先决条件

为了遵循本指南,您需要:

  • PostgreSQL 9.3 或更高版本
  • 用 C 语言或 Perl 语言编译的外部函数
  • PHP 8.0 或更高版本

步骤

1. 创建外部函数

首先,您需要创建一个外部函数。创建一个名为 add_numbers 的函数,它接受两个数字并返回它们的总和。以下是用 C 语言编写的外部函数示例:

#include <stdio.h>

extern int add_numbers(int a, int b) {
  return a + b;
}

或者是用 Perl 语言编写的示例:

sub add_numbers {
  my ($a, $b) = @_;
  return $a + $b;
}

2. 加载外部函数

接下来,您需要将外部函数加载到 PostgreSQL 中。为此,请使用 CREATE FUNCTION 语句,如下所示:

CREATE FUNCTION add_numbers(int, int)
LANGUAGE C RETURNS int
AS 'path/to/add_numbers'

对于 Perl 函数,使用以下语句:

CREATE FUNCTION add_numbers(int, int)
LANGUAGE plperl RETURNS int
AS 'add_numbers'

3. 在 PHP 中使用外部函数

现在可以通过 PHP 的 pg_query() 函数调用外部函数:

$dbh = pg_connect('host=localhost port=5432 dbname=database user=username password=password');

$result = pg_query($dbh, "SELECT add_numbers(3, 5)");

while ($row = pg_fetch_row($result)) {
  echo $row[0] . "n";
}

pg_close($dbh);

实战案例

假设您有一个名为 students 的表,其中包含 id, name 和 age 列。您希望创建一个外部函数来计算每个学生的平均成绩。

可以用 Python 编写的外部函数如下所示:

import psycopg2

def average_marks(student_id):
  conn = psycopg2.connect("host=localhost port=5432 dbname=school user=postgres password=my_password")
  cursor = conn.cursor()
  cursor.execute("SELECT AVG(marks) FROM marks WHERE student_id = %s", (student_id,))
  result = cursor.fetchone()
  cursor.close()
  conn.close()
  return result[0]

通过以下语句将函数加载到 PostgreSQL 中:

CREATE FUNCTION average_marks(int)
RETURNS float8
LANGUAGE plpythonu AS 'average_marks'

然后,您可以在 PHP 中使用以下代码来调用该函数:

$dbh = pg_connect('host=localhost port=5432 dbname=school user=postgres password=my_password');

$result = pg_query($dbh, "SELECT id, name, average_marks(id) FROM students");

while ($row = pg_fetch_row($result)) {
  echo $row[0] . " " . $row[1] . " " . $row[2] . "n";
}

pg_close($dbh);
卓越飞翔博客
上一篇: 忘记您所知道的关于字符串搜索的一切 - 尝试会让您大吃一惊!
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏