I have written PHP code which connects to MYSQL to look up information, sends it to an API, and get a response to write back into a new table.
Sometimes it works perfectly, other times it doesn’t. When it doesn’t it gives me this error
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' , , '', '', '')' at line 1
or sometimes it will write one or two entries into the new table and then give me the error at a different line. Oh, and even if I choose the same data for the API to look up and send, sometimes it will work and sometimes it won’t.( I have taken all commas out of the strings that are being sent to cut back on possible errors with commas.)
I’m wondering if this is a problem with the API or my code. I can’t understand how it would work for some of the time, and be a problem on the code problem, which leads to my thoughts on possible API problems.
My hypotheses are:
- The API key I have has limited functionality and so limits my results.
- It takes to long for a response and so times out my request.
Do either of these make sense? Any other ideas?
Here’s the php code that sometimes gets back something:
Sometimes it will echo out. But othertimes it won’t. The function $request->whatever are available in the API functions php.
I believe the sql line that is throwing the error has to do with this:
insertRow($db, $new_table, $Merchant, $ips, $scoreBeforeGeo, $geoFactor, $scoreAfterGeo, $category, $overall_protocol, $protocol_name);
function insertRow($db, $new_table, $Merchant, $ips, $scoreBefore, $geoFactor, $scoreAfter, $category, $overall, $protocol)
{
$insert = "INSERT INTO $new_table " . " VALUES('$Merchant', '$ips', $scoreBefore, $geoFactor, $scoreAfter, '$category', '$overall', '$protocol');";
$q = mysqli_query($db, $insert) || die(mysqli_error($db));
}
Again, sometimes it works and sometimes it doesn’t….
Your code does not sanitize the input to the query or pass it via parameters. This means that if the data being passed into the INSERT statement has characters (such as apostrophes) that will be interpreted as SQL syntax, it will mess up your statement. It also has the potential to destroy or provide unintended access to your data. In other words, it is a SQL injection attack waiting to happen.
Use prepared statements to guard against this. http://php.net/manual/en/mysqli.prepare.php