Is this code secure and valid? If so, can it be improved?
<?php
// conect to the data base
$mysqli = new mysqli('localhost','user','pass','dbname');
if($mysqli->connect_errno >0){
die( "problem with the connection");
}
// creat a function to get table information
function fetchTableFeildNames($mysqli , $databaseName , $tableName ){
$sql = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA`= '$databaseName' AND `TABLE_NAME`= '$tableName' ";
if(!$stmt =$mysqli->prepare($sql)){
die("There is an error with mysql preperation staetment".$mysqli->error);
}
if (!$stmt->execute()) {
echo "Execute failed: (" . $stmt->errno . ") " . $stmt->error;
}
$res = $stmt->get_result();
//looping throught the result
while ($array = $res->fetch_array()){
$newArray[] =$array;
}
return $newArray;
}
//insert function
function insert($mysqli,$tableName,$databaseName,$array){
//fetching table columns information
$tableColumns = fetchTableFeildNames($mysqli , $databaseName , $tableName );
// geeting table columns count
$tableColumnsCount = count($tableColumns);
//geting data array count
$dataArrayCount = count($array);
//see if the table columns count dosenot mutch array data count we kill the script
if ($tableColumnsCount != $dataArrayCount){
die("Data array dosenot mutch table columns count");
}
//forming the query depending on input array at same time we are geting data typs for the data array
$sql = "INSERT INTO `{$databaseName}`.`{$tableName}` VALUES (";
for($i=0;$i<$dataArrayCount;$i++){
$string = gettype($array[$i]);
//takeing the first litter example string= s ,integer =1
$a_param_type[] = $string[0];
$sql .= "?,";
}
//remove the last char ","
$sql = rtrim($sql , ",");
$sql .= ")";
$a_params = array();
$param_type = '';
$n = count($a_param_type);
//merging all types in one string
for($i = 0; $i < $n; $i++) {
$param_type .= $a_param_type[$i];
}
//passing the types to the array by refrence
$a_params[] = & $param_type;
//passing the data array by refrence
for($i = 0; $i < $n; $i++) {
$a_params[] = & $array[$i];
}
//preperaing the statment
if(!$stmt = $mysqli->prepare($sql)){
die("error in preperation " . $mysqli->error);
}
//using call_user_func_array() because mysqli::bind dont work with dynamic parameters
call_user_func_array(array($stmt, 'bind_param'), $a_params);
//executing the query
if(!$stmt->execute()){
die("error in executeing the query".$mysqli->error);
}
}
$array = array ("","catName" ,"catDesecription","","","","");
insert($mysqli,"items","yaztor",$array);
?>
db_functions.php
and include it). You should avoid naming things as simple asinsert
, its too generic. Maybedb_insert
orinsert_row
, etc. Just a few pointers. \$\endgroup\$ – Brandon Wamboldt Oct 28 '14 at 3:00