0

I'm trying to get the number of columns from a table :

$query = "select count(column_name) from information_schema.columns where table_name = '".$tableName."'";
$columns = pg_query($query);
echo $columns;

but instead of number I get a mysterious Resource id #61.
Converting to other types like string or int doesn't help.

6
  • Ever checked what pg_query() returns? Commented Oct 8, 2013 at 14:56
  • The syntax is $result = pg_query($conn, "SELECT author, email FROM authors"); as per the manual php.net/manual/en/function.pg-query.php Commented Oct 8, 2013 at 14:56
  • @Fred-ii- First argument is optional, so your comment gives nothing in that case. Commented Oct 8, 2013 at 14:59
  • as per manual pg_query() returns resource on success ... Commented Oct 8, 2013 at 15:00
  • @ElonThan: it's optional, true, but it's worth using, as I explained (or rather, touched on) in my answer Commented Oct 8, 2013 at 15:07

3 Answers 3

2

pg_query returns a resource to the query result, to get the actual rows, you can use any of the pg_fetch_* functions, such as pg_fetch_assoc

All this is well documented on php.net/pg_query. Look at the functions' signature:

resource pg_query ([ resource $connection ], string $query )
//return type function name (params)

Hence, what you need is:

$result = pg_query($query);
$columns = pg_fetch_all($result);
var_dump($columns);

Also, please get into the habit of passing the connection resource to the pg_query call explicitly... there's no telling what connection you're using, when working on a sizeable project, with multiple connections.

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

Comments

1

pg_query() returns resource and it's correct behaviour. You can check it in manual (what you definitely should do anyway).

To get rows from that resource you can use functions like pg_fetch_all() or pg_fetch_row(). Read about both and decide which one will be better in that case.

Comments

-1

You can try this

$query = "SHOW COLUMNS FROM '".$tableName."' ";
$result= pg_query($query);

if (!$result) {
  echo "An error occurred.\n";
  exit;
}
$i = 1;
while ($row = pg_fetch_row($result)) {
  echo "Column[$i] names: ".$row[0]."";
  echo "<br />";
  $i++;
}

echo "Column Count: ".$i;

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.