skiwi
skiwi

Reputation: 69269

PHP Using PDO and PDOStatement

I have the following class that takes care of the database interaction:

class DBH {
    private $dbh;

    public function __construct() {
        $this->dbh = new PDO("mysql:host=localhost;dbname=*", "*", "*");
    }

    public function query($query, $values) {
        if (!is_array($values)) {
            $values = array($values);
        }
        $statement = $this->dbh->prepare($query);
        $i = 1;
        foreach ($values as $value) {
            $statement->bindParam($i++, $value);
        }
        $statement->execute();
        return $statement;
    }

    public function num_rows($query, $values) {
        $statement = $this->query($query, $values);
        return $statement->rowCount();
    }

    public function insert($table, $keyvaluepairs) {
        $sql = "INSERT INTO `{$table}` (";
        $values_sql = ") VALUES(";
        $values = array();
        foreach ($keyvaluepairs as $key => $value) {
            $sql .= "`${key}`, ";
            $values_sql .= "?, ";
            $values[] = $value;
        }
        $query = substr($sql, 0, -2).substr($values_sql, 0, -2).")";
        return $this->query($query, $values);
    }

    public function close() {
        $this->dbh = null;
    }
}

Now I call the following:

$insert_statement = $dbh->insert("users", array(
    "email" => $email,
    "password" => $password,
    "ingame" => $ingame,
    "kiosk" => $kiosk
));

Is there a way to check if the $insert_statement was succesful?

I know that $statement->execute(); returns true or false upon execution, however I am returning the whole $statement.

If it is possible I'd like to use $statement to check whether the last execute() was succesful.
Else there is of course still the possibility to the query status caching in my DBH class.

Upvotes: 0

Views: 53

Answers (1)

Maciej Sz
Maciej Sz

Reputation: 12035

You could return a tuple containing both the $statement, and the boolean with execute() result. Or better yet: throw an exception on failure - this is what they are for.

Upvotes: 2

Related Questions