I am writing a DbAdapter in PHP. Trying to avoid sql injection attacks, for conditional selects, I need a way to check for the sanity of the SQL query that I am going to run. Given that prepared statements make the implementation very complicated, is there a quick way to check for the sanity of the sql query (WHERE clauses in particular as is the case here) before executing in the heart of the class? For example, a helper method to return false for malicious or suspicious queries will be fine.
My class code:
require_once './config.php'; class DbAdapter { private $link; /** * DbAdapter constructor. */ public function __construct() { $this->link = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME); if ($this->link->connect_errno) { die($this->link->connect_error); } } /** * @param $table * @param array $columns * @param string $condition * @return bool|mysqli_result */ public function select($table, $columns = [], $condition = "") { $colsString = $this->extractCols($columns); $whereString = $this->extractConditions($condition); $sql = "SELECT $colsString FROM `$table` " . $whereString; return $this->link->query($sql); } public function __destruct() { $this->link->close(); } private function extractCols(array $columns) { if(!$columns) { return '*';} else { $str = ""; foreach($columns as $col) { $str .= "$col,"; } return trim($str, ','); } } private function extractConditions(string $conditions) { if(!$conditions) { return ""; } else { $where = "WHERE "; foreach ($conditions as $key => $value){ $where .= "$key=" . $conditions[$key] . "&"; } return trim($where, "&"); } } }