dongmeiwei0226 2014-10-17 13:02
浏览 146
已采纳

使用PHP / PDO进行PostgreSQL UPDATE的RETURNING子句

I execute a simple postgresql update as:

UPDATE data SET Gender=lower(tmp.champs2) 
FROM tmp WHERE data.email=tmp.champs1 
AND (data.Gender IS NULL OR data.Gender='') 
AND tmp.champs2 IS NOT NULL 
AND tmp.champs2!='' 
RETURNING Gender

The PostgreSQL documentation said we can get the number of rows affected with the RETURNING clause.

But how can I get this result with PHP, PDO?

I try something like:

echo $requete = "UPDATE data 
    SET ".$value."=lower(tmp.champs".$num.") 
    FROM tmp 
    WHERE data.email=tmp.champs".$email." 
    AND (data.".$value." IS NULL OR data.".$value."='') 
    AND tmp.champs".$num." IS NOT NULL 
    AND tmp.champs".$num."!='' 
    RETURNING ".$value;

    $db->exec($requete);

    $db->fetch(PDO::FETCH_NUM);

    echo $row[0];

The correct number of rows updated are not returned.

  • 写回答

2条回答 默认 最新

  • douluanji8752 2014-10-18 14:14
    关注

    According to PDO's doc:

    PDO::exec() executes an SQL statement in a single function call, returning the number of rows affected by the statement.

    Your current code $db->exec($requete); ignores the return value, which is the mistake. This should be for instance:

    $affected_rows = $db->exec($requete);
    

    A RETURNING clause is not necessary to get the number of rows affected (besides, it doesn't exist in some backends that PDO supports). The purpose of RETURNING is to retrieve rows in addition to updating, all in the same query.

    In the case where the RETURNING clause is necessary and results must be fetched, PDO::query should be used instead of PDO:exec(). The PHP code to fetch the results is the same as if the query was a SELECT.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化