Reputation: 7955
I have the strangest problem. I wrote this very simple INSERT
query:
if(isset($_POST['putUser'])) {
$user = $_POST['user'];
$amount = $_POST['amount'];
$what = $_POST['what'];
$country = $_POST['country'];
$platform = $_POST['platform'];
$query = mysql_query('INSERT INTO sells(id, user, amount, what, country, platform) VALUES (NULL , '.$user.', 1, 1, 1, 1)');
if($query) {
echo 'ok';
} else {
die(mysql_error());
}
}
And it doesn't work. It works when I pust 1
in all values instead of, as in the example, $user
. But when the variables are present, it throws an error Unknown column 'Test username' in 'field list'
. Where's my mistake?
Upvotes: 3
Views: 1677
Reputation: 2790
You'r inserting field user(string) as non string try this:
if(isset($_POST['putUser'])) {
$user = mysql_real_escape_string($_POST['user']);
$amount = $_POST['amount'];
$what = $_POST['what'];
$country = $_POST['country'];
$platform = $_POST['platform'];
$query = mysql_query('INSERT INTO sells(id, user, amount, what, country, platform) VALUES (NULL , "'.$user.'", 1, 1, 1, 1)');
if($query) {
echo 'ok';
} else {
die(mysql_error());
}
}
As everybody say on comments, you shouldn't use the post info direct on mysql query, this make "sql injection atack" the easyiest thing on the world. You should scape some characters from string to prevent this. And do some research about PDO on PHP this link may help here
Upvotes: 6
Reputation: 13545
well the value you have passed to the query is not enclosed inside quotes. when you don't enclose a string inside quotes mysql assumes it's a field name. Also you have forgotten to escape your string.
$query = mysql_query('INSERT INTO sells (id, user, amount, what, country, platform) '
. 'VALUES (NULL , "' . mysql_real_escape_string($user) . '", 1, 1, 1, 1)');
Finally you should migrate away from using mysql
extension and use pdo
or mysqli
instead.
Upvotes: 7
Reputation: 4799
You need to wrap the string in quotes:
$query = mysql_query('INSERT INTO sells(id, user, amount, what, country, platform) VALUES (NULL , "'.$user.'", 1, 1, 1, 1)');
Upvotes: 0