Postgres SELECT SETOF功能重复记录

时间:2012-09-19 20:27:51

标签: php postgresql pdo

我将从Postgres FUNCTION返回SETOF到PHP / PDO。不幸的是,我得到了每行返回的2份副本。

这是Postgres TYPE:

CREATE TYPE marker AS (i BOOLEAN, r DOUBLE PRECISION, la DOUBLE PRECISION, lo DOUBLE PRECISION, n INTEGER);

功能:

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;

以下是相关的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");

意外行为是每个$lines是同一行的两个副本的数组。

E.G。当有一条记录要返回时$lines将是一个包含完全相同的2个字符串的数组。所以上面的日志记录将产生:

lines=Array
line=(f,10,51.505601,-0.109917,8)
line=(f,10,51.505601,-0.109917,8)

我理解我的内部PHP循环是无稽之谈,但它有效。我可以看到解决方法(例如添加break;)但想要删除重复。

我希望我已经清楚地解释了这一点。你能明白为什么我会得到每条记录的重复吗?

修改

关注@ a_horse_with_no_name的评论问题:

从phpPgAdmin调用SQL或FUNCTION 会产生副本。

1 个答案:

答案 0 :(得分:1)

我认为你错误地认为fetch()函数会返回多行 - 它总是返回一行 - 一列列。

默认$fetch_stylePDO::FETCH_BOTH,此数组在列名和0索引列号上都有索引,并且每列都有两个元素:

0 => (f,10,51.505601,-0.109917,8)
'rl_select_markers' => (f,10,51.505601,-0.109917,8)

所以:

  • 使用fetch(PDO :: FETCH_NUM),因此您将获得一个数字索引列;
  • 摆脱foreach ($lines as $line)
  • 将变量$lines重命名为$line
  • 只需使用$line[0]
  • 即可

更正后的代码:

while ($line = $stmt->fetch(PDO::FETCH_NUM)) 
{   
    $log->logInfo($log_id . " line=" . print_r($line,TRUE));
    $combined = array();
    // Remove brackets around $line and put in array
    $vals = explode(",", substr($line[0], 1, strlen($line[0])-2));
    // Combine into key value pairs
    $combined = array_combine($keys, $vals);
    $markers[] = array("m"=>$combined);
}

PHP GOTHA Nr 64372

更好:我会使用select (rl_select_markers (:lat, :lon)).*查询,然后只需:

while ( $combined = $stmt->fetch(PDO::FETCH_ASSOC) ) {
    $markers[] = array("m"=>$combined);
}