/** * Execute an SQL statement & get all records as hydrated objects. * * @access public * @param string $sql * @param integer $return * @return mixed */ public static function sql($sql, $return = SimpleOrm::FETCH_MANY) { // shortcuts $sql = str_replace(array(':database', ':table', ':pk'), array(self::getDatabaseName(), self::getTableName(), self::getTablePk()), $sql); self::$lastQuery = $sql; // execute $result = self::getConnection()->query($sql); if (!$result) { throw new \Exception(sprintf('Unable to execute SQL statement. %s', self::getConnection()->error)); } if ($return === SimpleOrm::FETCH_NONE) { return; } $ret = array(); while ($row = $result->fetch_assoc()) { $ret[] = call_user_func_array(array(get_called_class(), 'hydrate'), array($row)); } $result->close(); // return one if requested if ($return === SimpleOrm::FETCH_ONE) { $ret = isset($ret[0]) ? $ret[0] : null; } return $ret; }
/** * Give the class a connection to play with. * * @access public * @static * @param mysqli $conn MySQLi connection instance. * @param string $database * @return void */ public static function useConnection(mysqli $conn, $database) { self::$conn = $conn; self::$database = $database; $conn->select_db($database); }
<?php include_once dirname(__FILE__) . "/SimpleOrm.class.php"; $conn = new mysqli('localhost', 'grease_rat', 'grease_rat'); if ($conn->connect_error) { die(sprintf('Unable to connect to the database. %s', $conn->connect_error)); } if (!$conn->set_charset("utf8")) { die(printf("Ошибка при загрузке набора символов utf8: %s\n", $conn->error)); } SimpleOrm::useConnection($conn, 'grease_rat');
<?php // Load parameters. $params = parse_ini_file(sprintf('%s/parameters.ini', __DIR__), true); // Include the SimpleOrm class include 'SimpleOrm.class.php'; // Connect to the database using mysqli $conn = new mysqli($params['database']['host'], $params['database']['user'], $params['database']['password']); if ($conn->connect_error) { die(sprintf('Unable to connect to the database. %s', $conn->connect_error)); } // Tell SimpleOrm to use the connection you just created. SimpleOrm::useConnection($conn, $params['database']['name']); // Define an object that relates to a table. class Blog extends SimpleOrm { } // Create an entry. $entry = new Blog(); $entry->title = 'Hello'; $entry->body = 'World!'; $entry->save(); // Use the object. printf("%s\n", $entry->title); // prints 'Hello'; // Dump all the fields in the object. print_r($entry->get()); // Retrieve a record from the table. $entry = Blog::retrieveByPK($entry->id()); // by primary key // Retrieve a record from the table using another column.