I'm building a custom CMS in PHP, and I had the idea to generate MySQL from an array. I'm guessing that's not the safest thing to do, as I'll be putting variables directly into prepared statements. I'm hoping someone more experienced could look at what I've done so far and give me some insight into how I can make this safer.
Here's the class that I store all my data manipulation methods in
abstract class MySQLData extends MySQLDataHelper {
// connection to database
abstract public function getConn();
// table name from concrete class
abstract public function getTable();
public function insert( $args ) {
try {
$stmt = $this->getConn()->prepare( $this->generateInsertSQL( $args ) );
foreach ($args as $arg => &$value) {
$stmt->bindParam(":{$arg}", $value);
}
$stmt->execute();
} catch (PDOException $e) {
echo "Insert error: " . $e->getMessage();
}
}
//............................................
// More methods below, including delete, select and update, but lets focus on 'insert' only to keep things simple.
}
Helper method class, including insert SQL generator
abstract class MySQLDataHelper {
public function generateInsertSQL( $args ) {
$columns = array_keys( $args );
$placeholders = implode(', :', $columns);
$columns = implode(', ', $columns);
return "INSERT INTO `{$this->getTable()}` ({$columns}) VALUES (:{$placeholders})";
}
}
Example use case
require_once 'core/Pages.php';
$pages = new Pages( $db->conn() ); // Pages extends MySQLData
$args = array(
'name' => 'New page',
'content' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quisquam, laboriosam!',
'enabled' => true);
$pages->insert( $args );
Note that the output from generateInsertSQL in this case would be:
INSERT INTO `pages` (name, content, enabled) VALUES (:name, :content, :enabled)
Reminder, this code works perfectly fine, I'd just like to know if it could be made safer.
Thank you. I'm new to SO so sorry if this is a bad question or in the wrong place.