0

I created a form to insert data into a database using PHP and MySQL. The form takes a first name and last name and inserts them into a database named tbl_sample. The web form is from this tutorial that uses php, mysql and angularjs. The code is available for download at near the bottom of the page. The problem is that I'm trying to insert data via web form below the angularjs table instead of the modal. Adding data using the modal portion of the application works but I want to eventually remove the modal and keep a visible form below the table. When I attempt to add new data of first name 'Hello' and last name 'World' I get an error of 'Column not found'.

Error

INSERT INTO tbl_sample (first_name, last_name) VALUES (Hello, World) SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Hello' in 'field list'

PHP

try {
    $fn = $_POST['first_name'];
    $ln = $_POST['last_name'];
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO tbl_sample (first_name, last_name)
        VALUES ($fn, $ln)";
    // use exec() because no results are returned
    $conn->exec($sql);
    echo "New record created successfully";
}
catch(PDOException $e)
{
    echo $sql . "<br>" . $e->getMessage();
}

$conn = null;

MySQL Table

mysql> DESCRIBE tbl_sample;
+------------+--------------+------+-----+---------+----------------+
| Field      | Type         | Null | Key | Default | Extra          |
+------------+--------------+------+-----+---------+----------------+
| id         | int(11)      | NO   | PRI | NULL    | auto_increment |
| first_name | varchar(250) | NO   |     | NULL    |                |
| last_name  | varchar(250) | NO   |     | NULL    |                |
+------------+--------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)
Dharman
  • 30,962
  • 25
  • 85
  • 135
sg2019
  • 39
  • 4

1 Answers1

-2

String values must be enclosed into '

INSERT INTO tbl_sample (first_name, last_name) VALUES ('Hello', 'World')
Nikolai Shevchenko
  • 7,083
  • 8
  • 33
  • 42