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.
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.
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.
You can try this
$query = "SHOW COLUMNS FROM '".$tableName."' ";
$result= pg_query($query);
if (!$result) {
echo "An error occurred.
";
exit;
}
$i = 1;
while ($row = pg_fetch_row($result)) {
echo "Column[$i] names: ".$row[0]."";
echo "<br />";
$i++;
}
echo "Column Count: ".$i;