I have this function to ease out the task of inserting data into databases. I am not very sure if it is secure to use it this way.
Any suggestions on improving it?
function insert_into($query,$datatype) {
//$i=0; num=1; $i=1; num=2; for(i=1;)
$num=func_num_args()-1;
global $CONN;//set the global connection variable on.
for($i=2;$i<=$num;$i++) //assign the 'n' variables to an array
{
$values[$i]=mysqli_real_escape_string($CONN,func_get_arg($i));
if(empty($values[$i])|| !isset($values[$i])|| $values[$i]=="")
{
die("<p><b>Fatal Error:</b> One or more parameters have an uninitialized or empty variable. You can't use an empty variable as a parameter.</p>");
}
}
$blanks=str_repeat("?,", count($values)); //get the parameterized values as "?".
$blanks=trim($blanks,","); //remove the extra ","
$sql="INSERT INTO ".$query." VALUES (".$blanks.");"; //make the query
//set the connection
$stmt= $CONN->prepare($sql); //prepare the query
$bind=array();
foreach ($values as $key => $val) {
$bind[$key]=&$values[$key];
}
array_unshift($bind,$datatype);
call_user_func_array(array($stmt,'bind_param'),$bind); // bind the variables
#Replaced with above line ^ $stmt->bind_param($datatype, $xid);
if($stmt->execute()) // set parameters and execute
{
$stmt->close();
return 1; //sucessful
} else {
echo mysqli_error($CONN);
$stmt->close();
return 0;
}
$stmt->close();
//close anyway
}
//SAMPLE: set_conn(); insert_into("tablename (stuff1, stuff2, stuff3)","sss",$val1,$val2,$val3);
// set_conn() is another function which sets the connection to the database.
//The above function returns 1 on success.
Does this have some serious issues like SQL injection or any other vulnerabilities? Thanks!
$query
coming from? \$\endgroup\$insert_into("tablename (stuff1, stuff2, stuff3)","sss",$val1,$val2,$val3);
, here$query
is"tablename (stuff1, stuff2, stuff3)"
@Pimgd \$\endgroup\$$query
, it will be defined at the codes. User inputs will be go through the values of$val1, $val2, $val3...
. \$\endgroup\$