SQL查詢構建器:simple-query
SQL查詢構建器 - 簡單,但強大。
See on examples:
Simple SELECT query
$model = \Simple\Model(['table'=>'superA', 'alias'=>'A']);
$query = (new \Simple\Query($model))->where($model->field('username'), 'superUser');
echo $query->sqlSelect();
// SELECT A.* FROM superA AS A WHERE A.username = (?)
# use 'bindParameters' propriety to bind parameters in your database statement
$query->bindParameters
# ['superUser']
# more real example
$supossed_mysql_stmt = $con->prepare($query->sqlSelect());
# you can bind_param this way
foreach ($query->bindParameters as $value) {
$supossed_mysql_stmt->bind_param(
$query->type($value),#return 'i', 'd' or 's'
$value
);
}
...Why we not build onw string sql?
Using SQL Builder you can:
- create powerful query without specific order. - use bind values - create easy subquery conditions using query object - apply patterns to interprete request and build personal queries - not dependent of ORMs
About Model
Model allow to separate table structures to avoid conflicts when you want to create more complex queries.
Constructor
$model = new \Simple\Model([
'table' => 'nameOfTable',
'alias' => 'shortName',
'pk' => 'id' ## default value
]); pk()
Primary key of model
#example
$model = new \Simple\Model([
'table'=>'superA',
'alias'=>'A'
]);
echo $model->pk();
# A.id fk(\Simple\Model $modelB)
How key from model $modelB are represented inside of Model like a foreing key. Useful in joins
#example
$modelA = new \Simple\Model([
'table'=>'superA',
'alias'=>'A'
]);
$modelA = new \Simple\Model([
'table'=>'megaB',
'alias'=>'B'
]);
echo $modelA->fk($modelB);
# A.idMegaB field($fieldName)
Useful method return anti-collision field name
$modelA = new \Simple\Model([
'table'=>'superA',
'alias'=>'A'
]);
echo $model->field('name');
# A.name table()
Return table name
alias()
return alias table
Now We Can Build Queries!!
namespace My\Model;
class User extends \Simple\Model {
protected $table = 'user';
protected $alias = 'us';
}
$userModel = new \My\Model\User();
$query = new \Simple\Query($userModel);
$query->where($userModel->field('username'), $usernameParameter);
$stmt = $mysql_con->prepare($query->sqlSelect());
....
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!