質問

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;
    }
}
役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top