0

I'm trying to add revived form input into database.

<form action="index.php" method="post">
<input type="text" name="firstname" id="firstname">
<br>
<input type="text" name="lastname" id="lastname">
<br>
<input type="submit" name="submit" value="Submit">
if(isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];

$query = "INSERT INTO users (firstname, lastname) VALUES ($firstname, $lastname)";
if($conn->query($query) === true) {
    echo "added";
}else {
    echo $con->error;
}

Example : Firstname = Jason / Lastname = Haw

After clicking on submit button, i see error message : Unknown column 'Jason' in 'field list'

Where is the wrong thing to do?

2
  • Please note: You are wide open to SQL Injections and should use parameterized prepared statements instead of manually building your queries. They are provided by PDO or by MySQLi. Never trust any kind of input. Commented Nov 22, 2020 at 16:59
  • Your code is not safe. Use prepared statements. Commented Nov 22, 2020 at 20:57

1 Answer 1

1

$query = "INSERT INTO users (firstname, lastname) VALUES ('$firstname', '$lastname')";

put single quote for $firstname.

but this is not a proper approach, you should use prepared statement. your query is risk of sql injection, because no escaping the input.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you so much. Why i need to add single quote? im new in mysql, i pass example step by step.
because $query is string. if you dont put single quote/double quote, the query will become INSERT INTO users (firstname, lastname) VALUES (abc, abc), the abc will treat as column name instead of value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.