-3

I'm trying to solve this issue for an hour and i have no more solutions. I need to form a sql statement using some variables and i think i need to escape the quotes inside $_POST because i get an error (Parse error: syntax error, unexpected '"')

Help!! Thanks

$counter=$_POST["counter"];

$x=1;
$p="('','$code','$procedure0','$check0')";

while($x<$counter)
{
$p.=",('','$code','$_POST["check".$x]','$_POST["procedure".$x]')";
$x++;
};

...

$sql="INSERT INTO `proceduri` VALUES $p;";
chitoiu daniel
  • 107
  • 2
  • 13
  • `Parse error: syntax error, unexpected '"'` would be a PHP error, not a mysql error. You should use parameterized queries though for your query. – chris85 Nov 12 '15 at 21:24
  • 1
    You close your string `",('','$code','$_POST["` <-- here. Use single quotes for string encapsulation then use the `.` for concatenating variables. – chris85 Nov 12 '15 at 21:25
  • Do you want to get SQL injected? Because this is how you get SQL injected. Use prepared statements! [PDO](http://php.net/manual/en/pdo.prepared-statements.php) / [mySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) – Sammitch Nov 12 '15 at 21:29

2 Answers2

1

Please notice that your $_POST array is inside the query. Correct syntax:

for ($x = 0; $x < $counter; $x++) {
    if ($x)
        $p .= ',';

    $p.="('','$code','" . htmlspecialchars($_POST["check".$x], ENT_QUOTES) . "','" . htmlspecialchars($_POST["procedure".$x], ENT_QUOTES) . "')";
}

I have added htmlspecialchars func to sanitize variables before sending them to SQL server - this will prevent some possible SQL injection. Please read this to do it best way:

How can I prevent SQL injection in PHP?

Community
  • 1
  • 1
Baumi
  • 1,745
  • 1
  • 17
  • 31
0
$counter = $_POST["counter"];

$x = 1;
$p = "('','$code','$procedure0','$check0')";

while($x<$counter) {
    $p.= ",('','$code','{$_POST["check".$x]}','{$_POST["procedure".$x]}')";
    $x++;
};

...

$sql="INSERT INTO `proceduri` VALUES $p;";

While this might work, please consider using a parameterized approach.

Jan
  • 42,290
  • 8
  • 54
  • 79