По мере того, как пишу обёртку для PDO(драйвер MySQL) возникли проблемы. Для начала весь класс обёртки.
class Database {
private static $instance;
private $pdo = array();
private $stmt;
private $nowConnection;
private function __construct() {
}
public static function instance() {
if (empty(self::$instance)) {
self::$instance = new self;
}
return self::$instance;
}
public function addConnection($host, $db, $user, $pass, $id, $port = false, $charset = "utf8") {
try {
if (!$port)
$port = ini_get("mysql.default_port");
$dsn = "mysql:";
$dsn .= "host={$host};";
$dsn .= "port={$port};";
$dsn .= "dbname={$db};";
$options = array(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES {$charset}",
);
if (!isset($this->pdo[$id])) {
$this->pdo[$id] = new PDO($dsn, $user, $pass, $options);
$this->pdo[$id]->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
}
$this->switchConnection($id);
} catch (PDOException $e) {
throw new DatabaseExeption("[Database.php]Error in switchConnection(): " . $e->getMessage());
}
}
public function switchConnection($id) {
if (isset($this->pdo[$id])) {
$this->nowConnection = &$this->pdo[$id];
} else {
throw new DatabaseExeption("[Database.php]Error in switchConnection(): There is no connections called {$id}");
}
}
public function query() {
$args = func_get_args();
$query = array_shift($args);
try {
if (empty($args))
$this->simplyQuery($query);
elseif (is_array($args[0]))
$this->stmtQuery($query, $args[0]);
else
$this->stmtQuery($query, $args);
} catch (PDOException $e) {
throw new DatabaseExeption("[Database.php]Error in query: " . $e->getMessage());
}
}
private function simplyQuery($query) {
$this->stmt = $this->nowConnection->query($query);
}
private function stmtQuery($query, $args) {
$this->stmt = $this->nowConnection->prepare($query);
$this->stmt->execute($args);
}
public function affectedRows() {
$this->rowCount();
}
public function numRows() {
$this->rowCount();
}
private function rowCount() {
try {
return $this->stmt->rowCount();
} catch (PDOException $e) {
throw new DatabaseExeption("[Database.php]Error in rowCount() " . $e->getMessage());
}
}
}
Клиентский код:
try {
$database = Database::instance();
$database->addConnection("localhost", "application", "root", "", "application");
$database->query("INSET INTO users VALUES(?,?)",null,"Spike");
echo $database->affectedRows();
} catch (DatabaseExeption $e) {
echo $e->getMessage();
}
Всё получается: и подключение, и запрос, и в базе данных строчка появляется.
Но не выводится количество затронутых строк. Это плохо. Я даже не знаю что делать. Был бы чудовищно благодарен помощи.
PS
Кол-во строк не выводится даже при SELECT запросах((
Спустя 1 час, 30 минут, 54 секунды (14.08.2012 - 22:31) Oyeme написал(а):
From the PDO Doc:
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action.
Спустя 18 минут, 5 секунд (14.08.2012 - 22:49) VladKamyshanov написал(а):
Цитата |
From the PDO Doc:
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement. Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned. Your application can then perform the correct action. |
Ок. Когда-то давно свойство stmt было объявлено как статическое. И при запросе self::$stmt->rowCount(); (о чудо) возвращалось нужное мне значение.
Спустя 1 минута, 38 секунд (14.08.2012 - 22:51) VladKamyshanov написал(а):
Цитата |
Когда-то давно свойство stmt было объявлено как статическое |
Просто объявлял как статическое т.к. не до конца разбирался singleton'e