0

I am trying to insert rows into a mysql database using a php form and cannot figure out why i am getting this error:

Error: INSERT INTO time ('emp_name', 'clockdate', 'start_at', 'end_at') VALUES ('John Smith','2018-05-01','08:00:00','12:00:00') 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 ''emp_name', 'clockdate', 'start_at', 'end_at') VALUES ('John Smith','2018-05-01' at line 1

Here is my code:

    $conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO time ('emp_name', 'clockdate', 'start_at', 'end_at')
VALUES ('".$_POST["Name"]."','".$_POST["Date"]."','".$_POST["Start"]."','".$_POST["End"]."')";

if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

And My HTML:

<form action="connect.php" method="post">
  <input type="hidden" name="act" value="run">

    <label id="Name"> Name:</label><br/>
    <input type="text" name="Name"><br/>

    <label id="Date"> Date:</label><br/>
    <input type="text" name="Date"><br/>

    <label id="Start"> Start Time:</label><br/>
    <input type="text" name="Start"><br/>

    <label id="End"> End Time:</label><br/>
    <input type="text" name="End"><br/>


  <input type="submit" value="insert">
</form>

<form action="select.php" method="get">
  <input type="hidden" name="act" value="run">
  <input type="submit" value="select">
</form>

Sorry if this question bothers you experienced programmers, ive been trying to figure this out for hours

Christian
  • 83
  • 4
  • Sorry, I don't understand, am I using quotes, double quotes, and back ticks wrong then? – Christian May 08 '18 at 17:31
  • 1
    Yes. Columns need to be surrounded with backticks, or not surrounded at all. Single/double quoted words are treated as strings instead. – aynber May 08 '18 at 17:32
  • 1
    You quoted the column names with single quotes. (Like `'emp_name'`.) That causes MySQL to interpret them as literal strings rather than identifiers. – Don't Panic May 08 '18 at 17:32
  • AH! thanks so much, it worked! – Christian May 08 '18 at 17:34
  • Also, the way that you're inserting the values directly from `$_POST` is vulnerable to SQL injection. You can read more about that here: https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php – Don't Panic May 08 '18 at 17:34

0 Answers0