Mentales
Mentales

Reputation: 135

Only numbers get inserted in sql

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

Answers (5)

Xint0
Xint0

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

geofftnz
geofftnz

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

Denis de Bernardy
Denis de Bernardy

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

Alex
Alex

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

mario
mario

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

Related Questions