1

i have this code that i have worked on and it is throwing an exception, but i cannot troubleshoot the cause.

$servername = "localhost";
$username = "root";
$password = "Jimranoot";

$first = $_POST["firstiename"];
$last = $_POST["lastiename"];

$sql = "INSERT INTO RegisteredUsers (firstname, lastname)
VALUES ($first, $last)";
$conn = new PDO("mysql:host=$servername;dbname=jimmyneutron", $username, $password);

try {
  if (!empty($first) && !empty($last)) {
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->exec($sql);
    echo "Recorded Successfully!";
  } else {
    echo "Field Must Not Be Empty!";
  }
} catch (PDOException $e) {
  print "WRONG";
}

When i run this code by supplying inputs from HTML, it simply returns "WRONG". Thank you in advance for your help!

Darryl
  • 19
  • 1
  • What does the exception message say? Print this after the WRONG: `print $e->getMessage();` – Paul T. Oct 12 '19 at 20:08
  • $con should have come before $sql – gbenga wale Oct 12 '19 at 20:13
  • SQLSTATE[42S22]: Column not found: 1054 Unknown column 'abc' in 'field list' @PaulT. – Darryl Oct 12 '19 at 20:59
  • Though you have the potential for injection issues (as mentioned by others), string values in the SQL should be enclosed within single quotes: `...VALUES ('$first', '$last')`. ... assuming that `abc` was one of the values provided. – Paul T. Oct 12 '19 at 21:41
  • Yes! it is working already! Thank you so much Paul! i added the single quotes and it worked! – Darryl Oct 13 '19 at 07:26

0 Answers0