user3098638
user3098638

Reputation: 43

mysql: 1 INSERT INTO query two result

I have a table user (id VARCHAR(5), name VARCHAR(30))

I used INSERT INTO query in two way:

1) Directly:

...
$sql="INSERT INTO user (id,name) VALUES ('00001','abcd');
...

---> result: id(00001), name(abcd).

That's the right result.

2) By function:

function insert($id,$name)
{
    $sql="INSERT INTO user (id,name) VALUES ($id,$name)";
    ....
}

I used this function with 2 kind of parameter a)

insert('00001','00123');

---> result: id(1), name(123) (all zeros have been cut).

b)

insert('00001','abcd');

---> error: Unknown column 'abcd' in 'field list'.

I want to ask: why all the zeros have been cut, and why when I used a string value it make an error. How can I fix it to get right result by function. Many thanks!

Upvotes: 0

Views: 102

Answers (1)

Marc B
Marc B

Reputation: 360572

You never bothered quoting your values:

INSERT INTO user (id,name) VALUES ($id,$name)
                                   ^^^^^^^^^---here

So the query becomes

INSERT INTO user (id, name) VALUES (1, abcd)

Without the quotes, abcd is seen as a FIELD NAME, not a value. Since your table has no field named abcd, you get your error. Try:

INSERT INTO user (id,name) VALUES ($id, '$name')

as a short-term fix (note the ' quotes around $name). Long term fix: Start using prepared statements and/or placeholders, which eliminate the need for this kind of quoting.

Upvotes: 4

Related Questions