I’m looking to build a function that will dynamically generate SQL and execute it using PDO and prepared statements without the column names/where clauses being hard coded.
The example below the where clause “Calories” and “Colour” are hard coded, I would like to have the functionality to be able to add additional criteria as well as less or no where clause if the situation demands.
$sth = $dbh->prepare('SELECT name, colour, calories
FROM fruit
WHERE calories < ? AND colour = ?');
$sth->execute(array($calories, $colour));
This is an insert function which allows you to pass in values dynamically that I created.
public function insert($table,$columnValueArray){
$columns = implode(",",array_keys($columnValueArray));
$sql = "INSERT INTO ".$table." (?) VALUES (?)";
$sth = $conn->prepare($sql);
foreach($columnValueArray as $singleArray){
$values = implode(",",$singleArray);
$sth->execute(array($columns),$values);
}
}
I want a similar function to this to create an update function, the problem is the update function requires a where clause which can change for each row in the array
I actually made a similar answer some time ago to this question:
PDO multi-Filter sql query
It will dynamically build a basic
WHEREclauses based upon named param binding from a$_POSTarray so it won’t work with?params but to be honest here I am unsure why you are relying on the order of arrays to stop SQL injection and other such attacks since the order of arrays cannot always be garanteed in PHP.