-1

Whats the issue in the following query....i am constantly receiving this error. Error: INSERT INTO Myguests (firstname,lastname,email)VALUES You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1

<?php  include("new_db.php");?>

<?php
if(!empty($_POST['f_name'])&&!empty($_POST['l_name'])
&&!empty($_POST['email']))
{       $sql = "INSERT INTO Myguests (firstname,lastname,email)VALUES";
        for($i=0;$i<$_POST['num'];$i++){
        $first_name = mysqli_real_escape_string($conn,$_POST['f_name'][$i]);
        $last_name  = mysqli_real_escape_string($conn,$_POST['l_name'][$i]);
        $Email      = mysqli_real_escape_string($conn,$_POST['email'][$i]);

  $sql.="('".$first_name."','".$last_name."','".$Email."')";

}
$sql =rtrim($sql, ',');
if (mysqli_query($conn, $sql)) {
    echo "Records Created";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}


}
    mysqli_close($conn);

    ?>
  • Use prepared statements instead of `mysqli_real_escape_string()` please https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php?rq=1 – bassxzero Feb 08 '19 at 18:48
  • you forgot the comma after the end ) here $sql.="('".$first_name."','".$last_name."','".$Email."'),"; – imvain2 Feb 08 '19 at 18:48
  • Using comma but still facing this error.. – beginner_developer Feb 08 '19 at 18:52
  • 1
    @beginner_developer Try adding a whitespace in `INSERT INTO Myguests (firstname,lastname,email)VALUES` between the parantheses and the `VALUES`. – Ayush Feb 08 '19 at 18:57

1 Answers1

0

I used this create table statement

CREATE TABLE `Myguests` (
 `firstname` varchar(11) ,
 `lastname` varchar(11) ,
 `email` varchar(11));

And this code

<?php

$_POST['f_name'][0] = "john";
$_POST['f_name'][1] = "will";
$_POST['f_name'][2] = "jane";
$_POST['l_name'][0] = "doe";
$_POST['l_name'][1] = "smith";
$_POST['l_name'][2] = "2x";
$_POST['email'][0] = "mail@mail.com";
$_POST['email'][1] = "mail2@mail.com";
$_POST['email'][2] = "mail3@mail.com";
$sql = "INSERT INTO Myguests (firstname,lastname,email) VALUES ";
for($i=0;$i<3;$i++){
$first_name = ($_POST['f_name'][$i]);
$last_name  = ($_POST['l_name'][$i]);
$Email      = ($_POST['email'][$i]);
  $sql.="('".$first_name."','".$last_name."','".$Email."'),";

}
$sql =rtrim($sql, ',');

And it worked, are you still getting the same error after you added the "," after the $sql.= ?

FedeCaceres
  • 140
  • 10
  • please try with the query resultant of my code, maybe you do not have what you think you have on `$_POST['f_name']` or the other parameters – FedeCaceres Feb 09 '19 at 14:58