I am returning a SETOF from a Postgres FUNCTION to PHP/PDO. Unfortunately, I am getting 2 copies of every row returned.
Here is the Postgres TYPE:
CREATE TYPE marker AS (i BOOLEAN, r DOUBLE PRECISION, la DOUBLE PRECISION, lo DOUBLE PRECISION, n INTEGER);
And the FUNCTION:
CREATE OR REPLACE FUNCTION rl_select_markers (latitude DOUBLE PRECISION, longitude DOUBLE PRECISION) RETURNS setof marker AS $$
DECLARE
ROW marker%ROWTYPE;
BEGIN
FOR ROW IN SELECT is_male, rate, lat, lon, (EXTRACT(EPOCH FROM CURRENT_TIMESTAMP - created_at)/60)::INTEGER FROM markers
WHERE expires_at > CURRENT_TIMESTAMP
ORDER BY ST_Distance(ST_Point(longitude, latitude), geog, FALSE) LIMIT 25
LOOP
RETURN NEXT ROW;
END LOOP;
RETURN;
END;
$$ LANGUAGE plpgsql;
Here is the relevant PHP:
$dbh = new PDO('pgsql:host=' . $host . ';dbname=' . $db, $user, $pw);
$stmt = $dbh->prepare("SELECT rl_select_markers (:lat, :lon)");
$stmt->bindParam(':lat', $lat, PDO::PARAM_INT);
$stmt->bindParam(':lon', $lon, PDO::PARAM_INT);
$stmt->execute();
$keys = array('i', 'r', 'la', 'lo', 'n');
$markers = array();
while ($lines = $stmt->fetch())
{
$log->logInfo($log_id . " lines=" . $lines);
$combined = array();
foreach ($lines as $line)
{
$log->logInfo($log_id . " line=" . $line);
// Remove brackets around $line and put in array
$vals = explode(",", substr($line, 1, strlen($line)-2));
// Combine into key value pairs
$combined = array_combine($keys, $vals);
}
$markers[] = array("m"=>$combined);
}
$dbh = null;
$stmt = null;
$log->logInfo($log_id . " Send 200 OK");
sendResponse(200, json_encode(array("mks"=>$markers)), "application/json");
The unexpected behaviour is that each $lines is an array of two copies of the same line.
E.G. When there is one record to return $lines would be an array of 2 strings that are exactly the same. So the above logging will produce:
lines=Array
line=(f,10,51.505601,-0.109917,8)
line=(f,10,51.505601,-0.109917,8)
I understand my inner PHP loop is nonsense but it works. I can see work arounds (such as add a break;)but want to remove the duplication.
I hope I have explained this clearly. Can you see why I am getting these duplicates of every record?
Edit
Following @a_horse_with_no_name’s comment question:
Calling the SQL or the FUNCTION from phpPgAdmin does not produce the duplicate.
I think that you’ve made a mistake thinking that
fetch()function would return multiple rows — it always returns one row — an array of columns.As default
$fetch_styleisPDO::FETCH_BOTHthis array is indexed on both column name and 0-indexed column number and has two elements for every column:So:
foreach ($lines as $line)$linesto$line$line[0]Corrected code:
PHP GOTHA Nr 64372
Even better: I’d use
select (rl_select_markers (:lat, :lon)).*query and then just: