Re: php + postgresql

From: Chris <dmagick(at)gmail(dot)com>
To: admin <mick(at)mjhall(dot)org>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: php + postgresql
Date: 2008-07-25 04:18:06
Message-ID: 488953FE.7020304@gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general


> 2.
> Another problem was that no matter how many times I checked and
> re-checked code, or which pg_fetch_* function I used, copying an array
> member and trying to use it later just would not work, eg
>
> while ($row = pg_fetch_array($query)) {
> $content = $row[0]
> }
>
> echo $content;

pg_fetch_array expects a result from a query, not an actual sql query.

You need something like this:

$query = "select id, name from tablename";
$result = pg_query($query);
while ($row = pg_fetch_array($result)) {
$content = $row[0];
}

> 3.
> Some examples I found used PHP's pg_num_rows() function to count the
> rows in a result, then iterated through them with a "for" loop ... is
> this required behaviour (PHP docs don't appear to discuss this)?

You used to have to do this but you don't any more.

The old style was something like:

<?php
....

$result = pg_query($query);
$rows = pg_num_rows($result);

for ($row_num = 0; $row_num < $rows; $row_num++) {
$db_row = pg_fetch_array($result, $row_num);
}

The new style works like:

<?php
....

$result = pg_query($query);
while ($row = pg_fetch_array($result)) {
$db_row = pg_fetch_array($result);
}

This was changed a lot time ago (according to the php manual - 4.1.0).

> 4.
> Another weird one was that this statement always failed:
>
> $name = "file.php";
> SELECT fld_content FROM tbl_page WHERE fld_name='$name'

Escape your data:

$name = 'blah';
$query = "SELECT fld_content FROM tbl_page WHERE fld_name='" .
pg_escape_string($name) . "'";

<shameless plug>
I have some intro guides here you might want to check out:

http://www.designmagick.com/category/2/
</shameless plug>

--
Postgresql & php tutorials
http://www.designmagick.com/

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Alexander Dobikov 2008-07-25 04:47:56 Sequence
Previous Message Chris 2008-07-25 04:06:39 Re: php + postgresql