diff --git a/migrations/init.sql b/migrations/init.sql new file mode 100644 index 0000000..23dc901 --- /dev/null +++ b/migrations/init.sql @@ -0,0 +1,25 @@ +/*创建新用户*/ +CREATE USER jun@localhost IDENTIFIED BY 'jun'; + +/*用户授权 授权jun用户拥有sf数据库的所有权限*/ +GRANT ALL PRIVILEGES ON sf.* TO jun@'%' IDENTIFIED BY 'jun'; + +/*刷新授权*/ +FLUSH PRIVILEGES; + +/*创建数据库*/ +CREATE DATABASE IF NOT EXISTS `sf`; + +/*选择数据库*/ +USE `sf`; + +/*创建表*/ +CREATE TABLE IF NOT EXISTS `user` ( + id INT(20) NOT NULL AUTO_INCREMENT, + name VARCHAR(50), + age INT(11), + PRIMARY KEY(id) +); + +/*插入测试数据*/ +INSERT INTO `user` (name, age) VALUES('harry', 20), ('tony', 23), ('tom', 24); \ No newline at end of file diff --git a/src/db/Model.php b/src/db/Model.php index 30661d8..695b434 100644 --- a/src/db/Model.php +++ b/src/db/Model.php @@ -25,7 +25,11 @@ public static function getDb() $database = 'sf'; $username = 'jun'; $password = 'jun'; - static::$pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password); + $options = [ + PDO::ATTR_EMULATE_PREPARES => false, + PDO::ATTR_STRINGIFY_FETCHES => false + ]; + static::$pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password, $options); static::$pdo->exec("set names 'utf8'"); } @@ -61,15 +65,21 @@ public static function primaryKey() * @param mixed $condition a set of column values * @return static|null Model instance matching the condition, or null if nothing matches. */ - public static function findOne($condition) + public static function findOne($condition = null) { - $sql = 'select * from ' . static::tableName() . ' where '; - $params = array_values($condition); - $keys = []; - foreach ($condition as $key => $value) { - array_push($keys, "$key = ?"); + $sql = 'select * from ' . static::tableName(); + $params = []; + + if (!empty($condition)) { + $sql .= ' where '; + $params = array_values($condition); + $keys = []; + foreach ($condition as $key => $value) { + array_push($keys, "$key = ?"); + } + $sql .= implode(' and ', $keys); } - $sql .= implode(' and ', $keys); + $stmt = static::getDb()->prepare($sql); $rs = $stmt->execute($params);