Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

mysql error occured when displaing the page

working with php and mysql as well. I have following create.php page and need save data to mysql table.

<?php
include "config.php";

if(isset($_POST['submit'])) {
    $first_name = $_POST['firstname'];
    $last_name = $_POST['lastname'];
    $email = $_POST['email'];
    $password = $_POST['password'];
    $gender = $_POST['gender'];
}

$sql = "INSERT INTO 'users' ('firstname','lastname','email','password','gender') VALUES ('$first_name','$last_name','$email','$password','$gender')"; // this is line 12

$result = $conn->query($sql);

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

$conn->close();


?>

but got following error message

Undefined variable: first_name in C:\wamp64\www\simple\create.php on line 12 <br> error:INSERT INTO 'users' ('firstname','lastname','email','password','gender') VALUES ('','','','','') You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''users' ('firstname','lastname','email','password','gender') VALUES ('','','',''' at line 1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

how to fix this?

>Solution :

You need to put the whole code logic inside the if(isset($_POST['submit'])) condition

What’s happening right now is: if there is no $_POST['submit'], your if won’t run, thus no variables are declared, but your SQL and rest of the code will still run and that’s why it says var not defined

if(isset($_POST['submit'])) { ... }

Coming to the next issue is of using backticks. You really shouldn’t have single quotes around the field name. You can use backticks (`) for table and column names, single quotes (‘) for strings. There is already an answer for it: When to use single quotes, double quotes, and backticks in MySQL

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading