douyiyi5284 2013-02-02 18:19
浏览 24
已采纳

如何在课堂上保存最后一个id?

there is a way to save the $id inside the class so I can use it next time I run the function?

so far I get the right $id inside the function after the query is executed, but when I re-run the function I get an uninitialised $id again.

class ShortURL {
    public $id;
    public $val2;

    function insert() {

        $conn = new PDO( DB_DSN, DB_USER, DB_PASS );
        $sql = "INSERT INTO art ( val1, val2 ) VALUES ( :val1, :val2 )";
        $st = $conn->prepare( $sql );
        $st->bindValue( ":val1", self::hash ( $this->id+1 ), PDO::PARAM_STR );
        $st->bindValue( ":val2", $this->val2, PDO::PARAM_STR );     
        $st->execute();
        $this->id = $conn->lastInsertId();
        $conn = null;
    }
}
  • 写回答

1条回答 默认 最新

  • dongshi6710 2013-02-02 20:10
    关注

    If you create a new instance of the class before you execute your function then the variable will get reset. So when you do the following:

    $insert = new ShortURL();
    $insert->insert();
    echo $insert->id;
    //You should see your value correctly
    $insert = new ShortURL();
    echo $insert->id;
    //Now that you initialized the function again, the value is cleared
    

    Try creating your class then reusing the same instance of the class.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源