PHPize Online / SQLize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
Copy Clear
Copy Format Clear
<?php #Insert('sdfsdf',['a' => 1, 'sdsd' => 2, 'ererfsd' => 'sfsdfsdfv']); $d = new db($mysqli); $d->insert('sdsdsd', []); class db { public function __construct($db) { $this->db = $db; } function Insert($tblname,$array) { // at least this protection but a whitelist should be really used if (preg_match('![^A-Za-z0-9_]!', $tblname)) { throw new InvalidArgumentException("Invalid table name: $tblname"); } $columns = ''; foreach ($array as $key => $value) { // at least this protection but a whitelist should be really used if (preg_match('![^A-Za-z0-9_]!', $key)) { throw new InvalidArgumentException("Invalid column name: $key"); } // whether to add a comma or not if ($columns) { $columns .= ','; } // identifiers MUST be wrapped in backticks $columns .= "`$key`"; } // a string like ?,?,?... $placeholders = str_repeat('?,', count($array) - 1) . '?'; // it's OK ti use s for all variables $types = $types = $types ?: str_repeat("s", count($array)); $query = "INSERT INTO `$tblname` ($columns) VALUES ($placeholders)"; $stmt = $this->db->prepare($query); $stmt->bind_param($types, ...array_values($array)); $stmt->execute(); } }
Show:  
Copy Clear