The rules of adding strings into a query are plain and simple:
- The string should be enclosed in quotes.
- Therefore, these quotes should be escaped in the data, as well as some other characters, using
mysql_real_escape_string()
So, your code becomes
$type = 'testing';
$type = mysql_real_escape_string($type);
$reporter = "John O'Hara";
$reporter = mysql_real_escape_string($reporter);
$query = "INSERT INTO contents (type, reporter, description)
VALUES('$type', '$reporter', 'whatever')";
mysql_query($query) or trigger_error(mysql_error()." in ".$query);
// note that when running mysql_query you have to always check for errors
But if you're going to add another part of query, the rules changes.
- To add a number, you have to cast it to its type implicitly.
For example:
$limit = intval($_GET['limit']); //casting to int type!
$query = "SELECT * FROM table LIMT $limit";
- To add an identifier, it's better to choose it from some sort of white list, consists of hardcoded values
For example:
if ($_GET['sortorder'] == 'name') {
$sortorder = 'name';
} else {
$sortorder = 'id';
}
$query = "SELECT * FROM table ORDER BY $sortorder";
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 become something like this:
$type = 'testing';
$reporter = "John O'Hara";
pquery("INSERT INTO contents (type, reporter, description) VALUES(?s, ?s, ?s)",
$type, $reporter,'whatever');
And there will be absolutely no need to worry about all these matters.