Correctly read PHP data types from Postgres

How do you compile integer data in Postgres via PHP?

My integers are strings as shown below: var_dump ( $_SESSION )

  'logged_in' => int 1
  'user_id' => string '9' (length=1)                 // should be int
  'a_moderator' => string '0' (length=1)             // should be int

      

I am compiling the values ​​with the following code, which is obviously the source of the problem after pg_prepare

and pg_execute

.

    while ( $row = pg_fetch_array( $result ) ) { 
        $user_id = $row['user_id'];
    }   

      

+2


source to share


2 answers


You can convert strings to integers using intval :

$str = "5";
$num = intval($str);

      

or by the type of coercion:

$str = "5";
$num = (int) $str;

//this works too
$num = (integer) $str;

      



some test code:

<?php
   $str = "10";
   $num = intval($str);
   //$num = (int)$str;

   if ($str === 10) echo "String";
   if ($num === 10) echo "Integer";
?>

      

Further reading:

Jugging type

+1


source


It is common for PHP database extensions to return all datatypes as a string, since some SQL datatypes cannot be represented in native PHP datatypes.



Example: PostgreSQL BIGINT

(8-byte integer data type) would overflow int

PHP type (unless PHP was compiled with 64-bit support) and must be distinguished as float

, which may lose precision.

+3


source







All Articles