Reading boolean correctly from Postgres by PHP

后端 未结 4 1143
野性不改
野性不改 2021-02-14 14:58

The main problem of this thread is moved to here about boolean datatype in PHP / Postgres.

The problem is the conversion of t and f to

相关标签:
4条回答
  • 2021-02-14 15:31

    Select boolean field from postgre as ::int and in php cast to bool.

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

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

    0 讨论(0)
  • 2021-02-14 15:35

    Try:

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

    It is a boolean, not a string.

    0 讨论(0)
  • 2021-02-14 15:42

    This isn't a direct answer to the question, but here's an example demonstrating that pg_*() functions do in fact return the postgres boolean true value as the PHP string '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]$
    
    0 讨论(0)
  • 2021-02-14 15:43

    I wrote a function in postgres to export boolean to PHP readable boolean:

    You just use it this way:

    SELECT php_bool(columna) from
    table
    

    Here is the function:

    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$
    
    0 讨论(0)
提交回复
热议问题