I have a form that has a variable number of input fields, and i now try to get these values in my database. I got this code from another question here and all the replies where implying that they got it working..so i think i'm doing something wrong here.
I get no error, it just enters one empty entry/row in my database every time i submit the form. The $_POST array is filled with all the data i need, it shows when i print_r it.
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (
!empty($_POST['homeTeam']) && !empty($_POST['awayTeam']) && !empty($_POST['homeWin']) && !empty($_POST['awayWin']) &&
is_array($_POST['homeTeam']) && is_array($_POST['awayTeam']) && is_array($_POST['homeWin']) && is_array($_POST['awayWin']) &&
count($_POST['homeWin']) === count($_POST['awayWin'])
) {
$homeTeam_array = $_POST['homeTeam'];
$awayTeam_array = $_POST['awayTeam'];
$homeWin_array = $_POST['homeWin'];
$awayWin_array = $_POST['awayWin'];
for ($i = 0; $i < count($homeTeam_array); $i++) {
$homeTeam = mysql_real_escape_string($homeTeam_array[$i]);
$awayTeam = mysql_real_escape_string($awayTeam_array[$i]);
$homeWin = mysql_real_escape_string($homeWin_array[$i]);
$awayWin = mysql_real_escape_string($awayWin_array[$i]);
$sql = "INSERT IGNORE INTO CalcOdds (homeTeam, awayTeam, homeWin, awayWin) VALUES ('$homeTeam', '$awayTeam', '$homeWin', '$awayWin')";
$conn->query($sql);
$conn->close();
}
}
echo "<pre>";
print_r($_POST);
echo "</pre>";
echo 'Done!';
}
?>
mysqliyou should be using parameterized queries andbind_paramto add user data to your query. DO NOT use manual escaping and string interpolation or concatenation to accomplish this because you will create severe SQL injection bugs. Accidentally unescaped data is a serious risk. Using bound parameters is less verbose and easier to review to check you’re doing it properly.mysqliis significantly less verbose, making code easier to read and audit, and is not easily confused with the obsoletemysql_queryinterface. Before you get too invested in the procedural style it’s worth switching over. Example:$db = new mysqli(…)and$db->prepare("…")The procedural interface is an artifact from the PHP 4 era whenmysqliAPI was introduced and should not be used in new code.$_POSTmysqli_andmysql_functions and where are you actually connecting to your database?