Dynamic PHP PDO insert method This is my attempt at making a class for dynamic PDO queries in PHP.

The code works, but I would like the hear what I can improve to make it more secure and readable.

class DB 

{


    private static $connection;


    public static function setConnection ($connection) 

    {

        static::$connection = $connection;

    }


    public static function insert($table, $data = []) 

    {

        try {

            $columnsArray = array_keys($data);
            $columnsString = implode(',', $columnsArray);

            $valuesArray = array_values($data);
            $valuesCount = count($valuesArray);

            $valuesPlaceholder = '';
            for ($i=0; $i &lt; $valuesCount; $i++) { 
                $valuesPlaceholder .= '?,';
            }
            $valuesPlaceholder = rtrim($valuesPlaceholder, ',');


            $query = "INSERT INTO $table ($columnsString) VALUES ($valuesPlaceholder)";

            $statement = static::$connection-&gt;prepare($query);

            $statement-&gt;execute($valuesArray);

        } catch (\PDOException $e) {

            die("Insert failed: " . $e-&gt;getMessage());

        }


    }

}


Usage example

//setting the connection in app entry point
$config = require_once "config.php";
$dbConnection = Connection::make($config['database']);

DB::setConnection($dbConnection);


//using DB class in a controller
class PostController

{
    //inserting a post to posts table with name and content columns
    public function create() 

    {

        $name = $_POST['postName'];
        $content = $_POST['postContent'];

        DB::insert('posts', [

            'name' =&gt; $name,
            'content' =&gt; $content

        ]);

        return redirect('somewhere');

    }


}
You are using the prepared statement with placeholders properly, so regarding security, I would only advise you to not display the actual error details to the end user -- you don't want naughty people getting any funny ideas.

As for readability, I try not to declare single-use variables, though it can be good to declare a single-use variable to clarify the data being processed.

I don't prefer the over-delimit, then rtrim() technique.  Building a temporary array of ? then imploding it with commas seems cleaner to me.

$columns = implode(',', array_keys($data));

$placeholders = implode(',', array_fill(0, count($data), '?'));

$values = array_values($data);