dshtze500055 2015-07-11 14:40
浏览 161

如何理解更新语句是否成功运行?

In my program I want update some information, so I used:

 return ($result->rowCount() == 1)? true: false;

this way, if you save information without any change, false is returned and this is not the result usually we expect.

I change my function to this one

try{
        $result=$db->prepare($sql);
            $result->execute($arr);
            return true; 
        }catch(Exception $e){
            return false;   
        } 

Is it the best way? Does this way guarantee that the update statement worked or not?

  • 写回答

1条回答 默认 最新

  • dpjw67160 2015-07-11 15:34
    关注

    Assuming your $db is instance of PDO

    When you run PDO::prepare you can detect sql syntax error and when you run PDO::execute you will be sure that syntax is correct. Then application is resposible for knowing if update should have updated something or not.

    So here is some sample code:

    function update($db, $sql)
    {
        $preparedSql = $db->prepare($sql);
    
        if(!$preparedSql) {
            // syntax error occured
            $errorInfo = $db->errorInfo();
            // handle error
            return false;
        }
    
        $db->execute($preparedSql);
        // note that rowCount returns 0 when none updated
        return $db->rowCount();
    }
    

    In your application

    $result = update($db, $sql);
    
    if($result === false)
    {
         // error occured
    } elseif($result === 0) {
         // zero rows updated
    } else {
         // some rows were updated
    }
    

    Note that it's not tested and for learning purposes only, update function should accept to bind parameters for real world application

    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100