根據條件查詢動態拼接sql語句
阿新 • • 發佈:2019-01-22
function append_where(&$sql, $has_where) { $sql .= $has_where ? ' AND ' : ' WHERE '; return $sql; } function demo($name = '', $age = '') { $sql = "SELECT * FROM `employee`"; $has_where = FALSE; if(!empty($name)) { $has_where = append_where($sql, $has_where); $sql .= "`name`='{$name}'"; } if(!empty($age)) { $has_where = append_where($sql, $has_where); $sql .= "`age`='{$age}'"; } echo $sql; }
demo('張三', '18');,輸出為:SELECT * FROM `employee` WHERE `name`='張三' AND `age`='18',demo('18');,輸出為:SELECT * FROM `employee` WHERE `name`='18'。