Skip to content

Commit

Permalink
Refine the findOne method and add the sql file
Browse files Browse the repository at this point in the history
  • Loading branch information
Harry Sun committed Feb 29, 2016
1 parent 5a60077 commit 3b08a5f
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 8 deletions.
25 changes: 25 additions & 0 deletions migrations/init.sql
Original file line number Diff line number Diff line change
@@ -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);
26 changes: 18 additions & 8 deletions src/db/Model.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'");
}

Expand Down Expand Up @@ -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);

Expand Down

0 comments on commit 3b08a5f

Please sign in to comment.