【问题标题】:Reading boolean correctly from Postgres by PHP通过 PHP 从 Postgres 正确读取布尔值
【发布时间】:2009-08-21 22:31:54
【问题描述】:

本帖主要问题移至here关于PHP / Postgres中的布尔数据类型。

问题在于tf 转换为truefalse,因为Postgres 存储truefalse


如何在 SESSION 中使用变量a_moderator

我通过

获取变量a_moderator的值

#1 获取变量的代码

    $result = pg_prepare($dbconn, "moderator_check_query", 
        "SELECT a_moderator 
        FROM users
        WHERE email = $1;"
    );
    $a_moderator = pg_execute($dbconn, "moderator_check_query", array($_SESSION['login']['email']));

    $rows = pg_fetch_all ( $a_moderator );
  
    foreach ( $rows as $row ) {
       $_SESSION['login']['a_moderator'] = $row['a_moderator'];
    } 

我使用失败

#2 我如何使用变量失败的代码

if ( $_SESSION['login']['a_moderator'] == 't' ) {
   // do this
}

我也未成功运行 true 等值代替 t。 SESSION 中的变量的值是f,这样

#3 输出告诉我变量的值

Array ( [login] => Array ( 
   [passhash_md5] => dd2f85814c35fd465c30b1472f5d3af8 
   [email] => nthoaeuntht@Thnatuh.comn 
   [logged_in] => 1 [user_id] => 13 
   [username] => oeauoeh 
   [a_moderator] => t ) 
)

【问题讨论】:

  • 您仍然无法使用 pg_fetch_array 正确获取数据。它需要 PGSQL_ASSOC 标志。
  • davethegr8:您建议我最好使用pg_fetch_all,然后简单地使用foreach 来读取数据。
  • davethegr8:我用pg_fethch_array 解决了这个问题。我仍然有同样的问题。

标签: php postgresql


【解决方案1】:

从 postgre 中选择布尔字段为 ::int 并在 php 中转换为 bool。

 "SELECT a_moderator::int 
        FROM users
        WHERE email = $1;"

$isModerator = (bool)$row['a_moderator'];

【讨论】:

  • 或者,您可以跳过 postgres 中的强制转换,并在 PHP 中进行转换:$isModerator=($row['a_moderator'] === 't');
  • @Frank Farmer,你不知道问题。想法是让数据库扩展php_mysql、php_pgsql、php_sqlite等之间的代码跨平台。
【解决方案2】:

这不是问题的直接答案,但这里有一个示例,证明 pg_*() 函数实际上将 postgres 布尔真值作为 PHP 字符串 't' 返回:

[example]$ cat scratch.php 
<?php
//connect to the database...
require_once 'db_connect.php';

//query
$rows = pg_fetch_all(pg_query('SELECT TRUE::bool AS true'));
//dump returned array, and test with type-safe identity comparator
var_dump($rows, $rows[0]['true'] === 't');

[example]$ php scratch.php 
array(1) {
  [0]=>
  array(1) {
    ["true"]=>
    string(1) "t"
  }
}
bool(true)
[example]$

【讨论】:

【解决方案3】:

我在 postgres 中写了一个函数来将布尔值导出为 PHP 可读的布尔值:

你只是这样使用它:

SELECT php_bool(columna) from
table

函数如下:

CREATE OR REPLACE FUNCTION php_bool(boolean)
RETURNS numeric LANGUAGE plpgsql

AS
$BODY$

BEGIN

  IF $1 = true THEN
    RETURN 1;
  ELSE
    RETURN 0;
  END IF;
END
$BODY$

【讨论】:

    【解决方案4】:

    试试:

    if ( $_SESSION['login']['a_moderator'] ) {
      // do this
    }
    

    它是一个布尔值,而不是一个字符串。

    【讨论】:

    • 不,postgres 布尔值以字符串形式返回(正如他的 print_r() 输出中的 't' 所证明的那样)。试试看。我保证,pg_* 永远不会将布尔行值作为实际的 PHP 布尔值返回。
    猜你喜欢
    • 2010-11-21
    • 2018-06-30
    • 2019-03-09
    • 2014-07-26
    • 1970-01-01
    • 2017-05-23
    • 2016-10-22
    • 1970-01-01
    相关资源
    最近更新 更多