1

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;
    }
}
user2035693
  • 193
  • 2
  • 16
  • Do you create a new object of the class before calling `insert()`? Either do not do that or use static attributes. – str Feb 02 '13 at 18:21
  • 2
    note that keeping track of the id will only be useful if you're just inserting to this one table. lastInsertId() isn't table specific. – James C Feb 02 '13 at 18:24
  • yes, I create a new object of the class first. I'll try with static to see if it works. I was thinking as last resort to get the id from database and use it :D – user2035693 Feb 02 '13 at 19:00

1 Answers1

0

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.

Holy Crap
  • 360
  • 1
  • 10
  • ahh.. you are so right. Since I can't reuse the same instance of the class, I guess my best options are to update the database using the right id right away, or save the $id value in a session. I guess the session idea is better. – user2035693 Feb 02 '13 at 21:47