I'm trying to insert values in the contents table. It works fine if I do not have a PHP variable inside VALUES. When I put the variable $type
inside VALUES then this doesn't work. What am I doing wrong?
$type = 'testing';
mysql_query("INSERT INTO contents (type, reporter, description) VALUES($type, 'john', 'whatever')");
Try this:
You need to put
'$type'
not just $typeIf the variables contain user input or other data you can't trust, be sure to escape the data. Like this:
As long as it is a string - you have to put it within quotes
And, yes, as Dani adviced: you should sanitize every string you put in the query with
mysql_real_escape_string()
That's the easy answer:
and you define
$name
whatever you want.And another way, the complex way, is like that:
The rules of adding strings into a query are plain and simple:
mysql_real_escape_string()
So, your code becomes
But if you're going to add the variable in another part of a query, the rules change.
For example:
For example:
To make it all simplified yet with guaranteed safety, one have to use some sort of placeholder system where the variable goes into a query not directly but via some proxy, called a placeholder.
So, your query call becomes something like this:
And there will be absolutely no need to worry about all these matters.
For the limited set of placeholders you can use PDO. Though for real life usage you will need extended set which is offered by but a few libraries, one of which is SafeMysql.