【问题标题】:How to get a specific part of pg_last_error如何获取 pg_last_error 的特定部分
【发布时间】:2016-11-11 07:06:56
【问题描述】:

我希望能够返回一个异常,而 php 做到了。但是,php 也会返回该特定异常的上下文,我不太喜欢前端用户看到它。有什么方法可以只显示错误部分而不是异常的上下文部分?

        $query3 = "INSERT INTO sis.enrolledsubject (offeringno, regno) 
        VALUES ('$offering','$regno')";
        if (pg_query($query3)) {
          echo "New subject added successfully!";
        } else {
          echo pg_last_error($dbconn);
        }

错误是这样的:

ERROR: //My exception string here//
CONTEXT: PL/pgSQL function resolveconflict() line 44 at RAISE

我只想显示错误而不是错误的上下文。我尝试了类似pg_result_error_field但无济于事的东西。我希望有人可以帮助我。谢谢!

【问题讨论】:

  • 它显示什么错误?
  • 类似这样的:ERROR: //My exception string here// CONTEXT: PL/pgSQL function resolveconflict() line 44 at RAISE 我只想显示错误部分而不是上下文部分
  • 我不是在检查错误,而是在检查我的 Insert 语句是否在触发器检查后成功通过。
  • 永远不要使用pg_query 进行带参数的查询。始终使用pg_query_params 来避免 SQL 注入漏洞。

标签: php postgresql


【解决方案1】:

这是SSCCE

<?php

function error_exit($msg)
{
  fwrite(STDERR, "ERROR: $msg\n");
  exit(1);
}

$db = pg_connect("");
pg_query("create temporary table test(id int primary key)")
  or error_exit(pg_last_error($db));

foreach ( array_slice($argv, 1) as $arg ) {
  pg_send_query_params($db, "insert into test(id) values ($1)", [$arg])
    or error_exit(pg_last_error($db));
  $result = pg_get_result($db)
    or error_exit(pg_last_error($db));
  if ( pg_result_status($result) == PGSQL_FATAL_ERROR )
    error_exit(pg_result_error_field($result, PGSQL_DIAG_MESSAGE_PRIMARY));
}

?>

试试看:

$ php test.php 1 2 2
ERROR: duplicate key value violates unique constraint "test_pkey"

$ php test.php 1 2 a
ERROR: invalid input syntax for integer: "a"

【讨论】:

    猜你喜欢
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2021-07-18
    • 1970-01-01
    相关资源
    最近更新 更多