I'm trying to order my blog posts by user defined category, i.e, the one they click on my blog page.
Here's my code thus far,
##########################################################
$cat = mysql_real_escape_string($_GET['category']);
#########开发者_StackOverflow社区#################################################
$sql = "SELECT * FROM php_blog WHERE category = $cat ORDER BY timestamp";
$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" . $sql . "<br />" . mysql_error());
But that gives me this error,
Can't select entry from table php_blog. SELECT * FROM php_blog WHERE category = Update ORDER BY timestamp You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Update ORDER BY timestamp' at line 1 Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/funding9/public_html/jbblog/htdocs/category.php on line 91
$sql = "SELECT * FROM php_blog WHERE category = '" . mysql_real_escape_string($cat) . "' ORDER BY timestamp";
The string needed to be quoted (in your example it was Update, needs to be 'Update'), and also I ran it through mysql_real_escape_string() to protect you from SQL Injection.
MySQL uses back ticks to allow you to escape names. You should be using something like the following:
$cat = mysql_real_escape_string($_GET['category'], $mysql_link);
$queryString = "SELECT * FROM `php_blog` WHERE `category` = '$cat' ORDER BY `timestamp`";
Supplying the link will make sure it is escaped for that connection, where different databases may have different configurations and require different things to be escaped in them.
You may also want to look into the use of prepared statements with MySQLi as well. That takes the difficulty out of knowing which input needs to be escaped, how it should be quoted and even some of the verification.
精彩评论