I want to insert rows in a database table with the precaution of SQL-injection. I'm using below flexible MySQL insert function, which enters a record in a given table. Is this the best approach or is there any other approach to do the same?
<?php
/**
* This code writes data in database. It also takes care of sql injection case
*
* Entry function name : mainFunc
* Entry function arguments :
* $payload = [
* 'tableName' => 'table_name',
* 'data' => ['column1_name' => column1_value, 'column2_name' => column2_value, etc]
* ];
*/
Class AddDBEntry {
private $dbName;
private $dbUserName;
private $dbPassword;
private $dbHost;
private $mysqli;
// $stmt = The SQL Statement Object
// $param = Array of the Parameters
public function dynamicBindVariables($stmt, $params) {
if ($params != null) {
// Generate the Type String (eg: 'issisd')
$types = '';
foreach($params as $param) {
if(is_int($param)) {
// Integer
$types .= 'i';
} elseif (is_float($param)) {
// Double
$types .= 'd';
} elseif (is_string($param)) {
// String
$types .= 's';
} else {
// Blob and Unknown
$types .= 'b';
}
}
// Add the Type String as the first Parameter
$bind_names[] = $types;
// Loop thru the given Parameters
for ($i=0; $i<count($params); $i++) {
// Create a variable Name
$bind_name = 'bind' . $i;
// Add the Parameter to the variable Variable
$$bind_name = $params[$i];
// Associate the Variable as an Element in the Array
$bind_names[] = &$$bind_name;
}
// Call the Function bind_param with dynamic Parameters
call_user_func_array(array($stmt,'bind_param'), $bind_names);
}
return $stmt;
}
public function mainFunc($payLoad) {
$tableName = $payLoad['tableName'];
$data = $payLoad['data'];
$this->mysqli = new mysqli($this->dbHost, $this->dbUserName, $this->dbPassword, $this->dbName);
if ($this->mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $this->mysqli->connect_errno . ") " . $mysqli->connect_error;
die();
}
$stmtString = 'insert into ' . $tableName . ' (' . implode(', ', array_keys($data)) . ')' . ' values ' . '(' . str_repeat('?, ', count($data) - 1) . '?)';
$params = array_values($data);
if (!($stmt = $this->mysqli->prepare($stmtString))) {
echo "Unable to prepare statement";
// stop here, $stmt is not set, cannot continue
die();
}
$stmt = $this->dynamicBindVariables($stmt, $params);
$stmt->execute();
if ($stmt->affected_rows <= 0) {
echo "Error in insert";
}
$stmt->close();
}
}
$addDBEntry = new AddDBEntry();
$payload = [ 'tableName' => 'users', 'data' => ['name' => 'test', 'mobile' => '7777777777', 'email' => '[email protected]'] ];
$addDBEntry->mainFunc($sendData);
\$\endgroup\$