Forum Moderators: coopster
$db_connection = mysql_connect("localhost", "root", "kipling") or die(mysql_error());
$db_select = mysql_select_db("larry_books", $db_connection) or die(mysql_error());
if($_POST['submit']){
$query = "insert into authors values('0', "$_POST['last_name']", "$_POST['first_name']")";
if(@mysql_query($query)){
echo 'The author has been added';
}else
{
echo 'The author has not been added'.mysql_error();
}
}
?>
<form action = "<?php echo $PHP_SELF?>" method = "post">
Last Name: <input type = "text" name="last_name" size = "50" maxlength = "50"/><br/>
First Name: <input type = "text" name="first_name" size = "30" maxlength = "30"/><br/>
<input type = "submit" name = "submit" value = "Submit"/>
</form>
</body>
</html>
$query = "insert into authors values('0', "$_POST['last_name']", "$_POST['first_name']")";
As you are using double-quotes in this line to separate literals and variables you need to use the string concatenation operator (.).
You could do away with the quotes and let PHP figure out what the variables should be, but I never do that. I think that line should read (additional string concatenation operators in bold):
$query = "insert into authors values('0', ".$_POST['last_name'].", ".$_POST['first_name'].")";
INSERT INTO table (field1,field2,field3) VALUES ('value1','value2','value3')
That way you have no argument over which columns you are trying to populate. Note also the apostrophe's around the field values (this may actually be what is causing your error). Whilst they are technically only required for string literals, I think it is good practice to delimit ALL values with apostrophe's, whatever the column type.
I would also have a look at the mysql_escapestring functions, as your script could be upset by apostrophe's within the input - certainly a possibility where people's names are concerned!
INSERT INTO authors(author_id, last_name, first_name) VALUES ('0', ".$_POST[\'last_name\'].", ".$_POST[\'first_name\'].")"
I tried that but it did not work..could you tell me how to do it..i have spent too much time on this ..one so I do now wish to read adn find out..I will appreciate if you can tell me...thanks
just a clarification in php if you want the quotes to be printed you have to escape it with \", right?
but it seems to print single quote you do not need to escape it...is that right?