I am doing a form with php/html and I want to insert details into my database using
$sql = "INSERT INTO membre (Name, Age) VALUES ('$Name', '$Age')";
I think there is something missing in my SQL code. How to solve it?
I am doing a form with php/html and I want to insert details into my database using
$sql = "INSERT INTO membre (Name, Age) VALUES ('$Name', '$Age')";
I think there is something missing in my SQL code. How to solve it?
First of all, you're using a MySQL reserved word as a column name (Name
). It is OK to do that as long as you surround your columns names in back ticks in your query:
$sql = "INSERT INTO membre (`Name`, `Age`) VALUES ('$Name', '$Age')";
If you're not preparing your queries it is quite possible that you'll run into errors because of names with apostrophes in them, such as "O'Shaughnessy". In this case, when not using prepared statement, you must make sure to escape all of your input in order to handle apostrophes properly. this would make the above input "O\'Shaughnessy". You can do this with one of the string escape functions PHP provides.
You're also at risk for SQL Injection Attacks. if you're not using prepared statements for your queries or properly cleansing data input by users.
Second, I am going to go out on a limb here and guess that you are using an older, deprecated database API, the mysql_*
functions. If you can, you should stop using mysql_*
functions. They are no longer maintained and are officially deprecated. Learn about prepared statements instead, and consider using PDO, it's really not hard.
First of all, when using MySQL as a database you want to put ` around the columns in your queries. This is good practice because then you tell MySQL that it should not be interpreted as keywords. Keywords such as name and datetime. So your query should look like this instead:
INSERT INTO membre (`Name`, `Age`) VALUES ('$Name', '$Age')
Also, when you are working with strings in PHP it's easy to miss ' and stuff. So I recommend you to make your SQL string look like this instead
$sql = "INSERT INTO membre (Name, Age) VALUES ('".$Name."', '".$Age."')";
Also, I think that what's causing you the most trouble is that membe is misspelled. I think what you mean is member. So, change your query to
$sql = "INSERT INTO member (`Name`, `Age`) VALUES ('".$Name."', '".$Age."')";
And it should work.
You can use escape string function "addslashes
" while inserting or updating the records.
$sql = "INSERT INTO membre (`Name`, `Age`) VALUES ('" . addslashes($Name) . "', '$Age')";
Try this
$sql = "INSERT INTO membre (Name, Age) VALUES (\'$Name\', \'$Age\')";
OR
$sql = "INSERT INTO membre (Name, Age) VALUES ('".$Name."', '".$Age."')";