Question

I'm working from the W3Schools tutorial for MySQL and it seems either some of the code is outdated or I'm just missing something utterly stupid. In trying to pass on information to a database, I get this error:

Error: Unknown column 'd' in 'field list'

I'm attempting to pass info on from a form submission that then links to this page, where it grabs the info the user enters to create a new entry into the database.

Here is the code for the form submission.

<html>
<body>

<form action="3ainsert.php" method="post">
Firstname: <input type="text" name="firstname">
Lastname: <input type="text" name="lastname">
Age: <input type="text" name="age">
<input type="submit">
</form>

</body>
</html>

Here is the code for the other page:

<?php
$con=mysqli_connect();
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// escape variables for security
$firstname = mysqli_real_escape_string($con, $_POST['firstname']);
$lastname = mysqli_real_escape_string($con, $_POST['lastname']);
$age = mysqli_real_escape_string($con, $_POST['age']);

$sql="INSERT INTO persons (FirstName, LastName, Age)
VALUES ($firstname, $lastname, $age)";

if (!mysqli_query($con,$sql))
{
  die('Error: ' . mysqli_error($con));
}
echo "1 record added";

mysqli_close($con);
?>
Was it helpful?

Solution

Your query isn't encasing the values in quotes:

$sql="INSERT INTO persons (FirstName, LastName, Age)
VALUES ('$firstname', '$lastname', '$age')";

However please note that generally using prepared statements is preferred over directly inserting into a query.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top