I am using PHP 7, MySQL. I had been coding for my project a long time and it now has thousands of MySQL queries. I was not aware of prepared statements then.
Now, to avoid SQL injection, I want to use prepared statements but it is difficult for me to convert all of them one by one to prepared statement.
Is there any way I could parse a normal statement and convert it to prepared statement automatically using PHP? For every MySQL query, I pass it to a PHP function before passing to MySQL command.
public function dbquery($query,$dbname,$dbclose="-1")
{
$this->mysqli->select_db($dbname);
$GLOBALS["dbr_total"]++;$GLOBALS["dbr_query"]++;
$colarr=Array();$tares=Array();
if ($result = $this->mysqli->query($query))
{
$GLOBALS["dbretry"]=0;
$finfo = $result->fetch_fields();
$c=0;
foreach ($finfo as $val)
{
$colarr[$c]=$val->name;//get all colum names in this array
$c++;
}
$co=0;
while($obj = $result->fetch_object())
{
for($k=0;$k<count($colarr);$k++)
{
$elem=$colarr[$k];
$tares[$co][$elem]=$obj->{$colarr[$k]};
}
$co++;
}
if($co==0)
{
$GLOBALS["dbretry"]=0;
if($dbclose!="-1"){$this->dbclose();}
return EMPTY_RESULT;
}
}
else
{
if($GLOBALS["dbretry"]>3)
{
$GLOBALS["dbretry"]=0;
$errmsg=$this->mysqli->error;
$errno=$this->mysqli->errno;
if($dbclose!="-1"){$this->dbclose();}
$errobj=new ta_errorhandle();
$errobj->senderror("OOPS! Could Not process your query!".$errmsg,$errno,"1");
}
else
{
$GLOBALS["dbretry"]++;
$this->dbquery($query,$dbname);
}
}
//QUERY DONE
if($dbclose!="-1"){$this->dbclose();$result->close();}
unset($obj);unset($finfo);unset($query);unset($result);unset($colarr);unset($c);unset($co);
return $tares;
}
public function dbinsert($query,$dbname,$dbclose="-1")
{
$this->mysqli->select_db($dbname);
$GLOBALS["dbr_total"]++;;$GLOBALS["dbr_insert"]++;
if (!$this->mysqli->query($query))
{
$errmsg=$this->mysqli->error;
$errno=$this->mysqli->errno;
die("<br><br>".$errmsg."<br><br>".$errno);
if($GLOBALS["dbretry"]>3)
{
$GLOBALS["dbretry"]=0;
$logobj=new ta_logs();
$logobj->store_templogs("PROBLEM EXECUTING QUERY:".$query." ON ".$dbname);
return $this->mysqli;
}
else
{
$GLOBALS["dbretry"]++;
$this->dbinsert($query,$dbname);
}
}
else
{
$GLOBALS["dbretry"]=0;
}
if($dbclose!="-1"){$this->dbclose();}
return SUCCESS;
}
Now what I do is call $dbobj->dbquery("my query","database name");
where $dbobj is an object for the class of these functions.
How do I convert these functions so that whatever query I receive as parameter is used and converted to prepared statements? I cant rewrite every query in my code. I have written more than 10,000+ queries already.