Reputation: 135
So i have this form
<form>Tag name:
<input type='text' name='tagname' />
<input type='submit' value='Add' />
<input type='hidden' name='id' value='$id' />
</form>
<hr />
it runs this script
if ($tagname)
{
mysql_query("INSERT INTO tags (id, tag) VALUES ($id, $tagname)");
?>
<script type="text/javascript">
alert("Tag added.");
history.back();
</script>
<?php
}
If i insert numbers in form it gets added to sql database nicely,but if it consist of alphabetical characters i get the alert but nothing is inserted in database. I checked phpmyadmin if the structure is wrong(text/varchar/int...) tried most of them but it is the same.
Upvotes: 0
Views: 245
Reputation: 5399
I see a couple of issues with your code, first setting the value for the id input field:
<input type="hidden" name="id" value="<?php echo $id; ?>" />
And then, in the SQL you should use quotes:
mysql_query("INSERT INTO tags (id, tag) VALUES ($id, '$tagname')");
Upvotes: 2
Reputation: 10102
You need quotes around $id (unless it's a number) and $tagname in your mysql query.
As a side note, this is vulnerable to SQL injection.
Upvotes: 3
Reputation: 78523
In so far as I can tell based on your code, and depending on how you're escaping, if you've no ajax to fetch the id you're running either of:
INSERT INTO tags (id, tag) VALUES (0, $tag)
INSERT INTO tags (id, tag) VALUES ('', $tag)
You should really be running:
INSERT INTO tags (tag) VALUES ('$tag')
Upvotes: 1
Reputation: 14628
mysql_query("INSERT INTO tags (id, tag) VALUES ($id, '$tagname')");
Very common mistake. Think about escaping, or better - parametrizing queries. Concatenating an SQL query is an awful approach (so is putting in a small piece of code, together, HTML, PHP, SQL and JavaScript)
Upvotes: 3
Reputation: 145492
You need single quotes to enclose strings within SQL queries:
mysql_query("INSERT INTO tags (id, tag) VALUES ('$id', '$tagname')");
And I'm conjecturing you also forgot to apply mysql_real_escape_string
beforehand.
Upvotes: 3