I am trying to loop through a number of results from a form, but can't get it quite right.
for ($i=1;$i<$total;i++)
{
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}','{$_POST['$iH']}', '{$_POST['$iA']}'");
}
I want $_POST['$iH']
to be the same as $_POST['1H']
,$_POST['2H']
, $_POST['3H']
etc.
Like so:
for ($i = 1; $i < $total; $i++) { // <--- You had a typo here
$sql = "INSERT INTO MYSQL(value1,value2,value3) ";
$sql .= "VALUES('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
mysql_query($sql);
}
But, two big problems.
Boy, what a waste! Dispatch one instead:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}','" . $_POST[$i . 'H'] . "', '" . $_POST[$i . 'A'] . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
It continues to baffle me how, in 2011, people are still not getting this.
If you're going to insist upon using the ancient mysql
API (not even the OO version?!) rather than PDO, get into the habit of sanitising your inputs:
$rows = Array();
for ($i = 1; $i < $total; $i++) {
$rows[] = "('{$i}'," .
"'" . mysql_escape_string($_POST[$i . 'H']) . "'," .
"'" . mysql_escape_string($_POST[$i . 'A']) . "')";
}
$sql = "INSERT INTO MYSQL(value1,value2,value3) VALUES('" . implode("','", $rows) . "')";
mysql_query($sql);
OK, so without multi-query support in your API it's unlikely to cause you significant grief here, but it can do in authentication routines. Just get used to scripting properly in this regard.
You really need to escape your post variables with mysql_real_escape_string()... you are seriously looking for trouble like that.
In answer to your question, I think you need to do something like this:
mysql_query("INSERT INTO MYSQL(value1,value2,value3) VALUES('{$i}', '" . $_POST[$i . 'H'] . "', '" . $_POST[$i.'A']. "'");
with the letters rubbing up against your variable, the php engine will assume they are part of the variable name; that variable name does not exist, so you will get some strange results.
You need to escape your quotes because your variable is being passed as a literal:
for ($i=1; $i<$total; $i++)
{
mysql_query('INSERT INTO MYSQL(value1,value2,value3) VALUES("' . $i . '","' . $_POST[$i . 'H'] . '", "' . $_POST[$i . 'A'] . '")');
}