3

How do you compile integer data in Postgres by PHP?

My integers are string as the following show by 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 compile the values by the following code which obviously is the source of the problem after pg_prepare and pg_execute.

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

2 Answers 2

4

It's ordinary for PHP database extensions to return all data types as string, because some SQL data types cannot be represented in PHP native data types.

Example: PostgreSQL BIGINT (8-byte integer data type) would overflow the int PHP type (unless PHP is compiled with 64-bit support), and be cast as float which might lose exactness.

Sign up to request clarification or add additional context in comments.

Comments

1

You can convert strings to integers using intval:

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

or by type 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:

Type Jugging

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.