When you take user input and put it into a query, you are at risk for SQL Injection. The Wikipedia article on SQL Injection has some pretty useful information about it and how to avoid it.
In a nutshell, you have to be careful with the user input to make sure someone is not scheming against your query generation code. Take for example this script:
$user_input = $_GET["q"];
$sql = "SELECT * FROM user_table WHERE some_column='$user_input'";
$query = mysql_query($sql) or die("There was an error:" . mysql_error());
Imagine that a user were to access this script on your site using the following value for q:
localhost/chump.php?q=%27%20UNION%20SELECT%20sd.password%20as%20username%20FROM%20sensitive_data%20sd%20WHERE%20sd.username%3D%22some_other_user%22
This would make your query look something like this:
SELECT * FROM user_table WHERE some_column='' UNION SELECT sd.password as username FROM sensitive_data sd WHERE sd.username="some_other_user"
I'm not sure if that would actually get me a password from the table sensitive_data, but you should get the idea: If you just take user input and stuff it in your query, you are at risk of SQL injection.
How can you protect yourself against this? There are a few ways:
1) Validate your data to make sure it's the type of input you expect. Use functions like [man]preg_match[/man] or [man]filter_var[/man] to make sure input values are what you expect them to be. This works great for numeric inputs or for email addresses or urls or other common types of input like alphanumeric indentifiers, but will not work very well against free-form text or other long-form inputs.
2) Escape user input with functions like [man]mysqli_real_escape_string[/man] if you are using MySQL or [man]pg_escape_string[/man] if you are using PostgreSQL. These escape functions take care to turn certain chars (NUL (ASCII 0), \n, \r, \, ', ", and Control-Z) into their 'escaped' equivalents as necessary. An escaped equivalent of ' would be \', etc. if you escaped the user input in the example above, the query would end up looking for a record in user_table where some_column was the query string, rather than letting the attacker formulate an entirely different query.
3) Use prepared statements. Depending on how you use them, prepared statements take care of escaping the values you are putting in your query and adding quotes around text values and such. The documentation has good examples. Note that the use of prepared statements alone doesn't guarantee safety against SQL injection. You still have to pay attention to how you are using user input to construct your query.