Pro tip: use new lines and try to keep the code within the first 80 (maybe occasionally up to 100) columns in your editor. Putting it all on one line does not make it process faster. For instance, instead of 2 very long lines, something like:
$stmt_2 = mysqli_prepare(
"INSERT INTO trailing_histories(
) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)"
That is much easier to read and debug.
And as far as that query goes, since you are using a prepared statement and binding variables for all external inputs, you are safe from SQL injection. I did not, however, go over all your code line by line -- nor is anyone else likely to do so, as ginerjm points out.