• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 477
  • Last Modified:

How to fix MySQL Injection, please help me

my code:

if (isset($_GET['type'])) $type = $_GET['type'];
else $type = 'all';

if (isset($_GET['subcat_id'])) {
	$subcat_id = $_GET['subcat_id'];
	$cat_res = my_query('SELECT CD_name, CD_cat_id FROM subcategories WHERE RW_id='.$subcat_id);
	$subcat_name = mysql_result($cat_res, 0, 0);
}

if (!isset($_GET['cat_id'])) {
	$cat_id = mysql_result($cat_res, 0, 1);
} else $cat_id = $_GET['cat_id'];
$cat_res = my_query('SELECT CD_name FROM categories WHERE CD_id='.$cat_id);
$cat_name = mysql_result($cat_res, 0);

if (isset($_GET['brand_id'])) {
	$brand_id = $_GET['brand_id'];
}

Open in new window


http://domain.com/session.php?cat_id=2'

Error:
SELECT CD_name, CD_cat_id FROM subcategories WHERE CD_id=3\'
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 '\'' at line 1

Open in new window


how to fix error
0
inside7
Asked:
inside7
1 Solution
 
Dave BaldwinFixer of ProblemsCommented:
Why are you putting the single quote after the value in your url?  The \' is the escape code for the single quote.
0
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:
this should work better:

$type = '';
$subcat_id = '';
$cat_res = '';
$subcat_name = '';
$cat_id = '';

if (isset($_GET['type'])) $type = $_GET['type'];
else $type = 'all';

if (isset($_GET['subcat_id'])) {
	$subcat_id = $_GET['subcat_id'];
	$cat_res = my_query('SELECT CD_name, CD_cat_id FROM subcategories WHERE RW_id='.$subcat_id);
	$subcat_name = mysql_result($cat_res, 0, 0);
}

if (!isset($_GET['cat_id'])) {
	$cat_id = mysql_result($cat_res, 0, 1);
} else $cat_id = $_GET['cat_id'];

$cat_id = mysql_real_escape_string($cat_id);

$cat_res = my_query('SELECT CD_name FROM categories WHERE CD_id='.$cat_id);
$cat_name = mysql_result($cat_res, 0);

if (isset($_GET['brand_id'])) {
	$brand_id = $_GET['brand_id'];
}
                                  

Open in new window

0
 
Roger BaklundCommented:
Whenever you use $_GET (or $_POST or $_REQUEST) you must also validate and/or filter the input. For integers, a simple casting will do:

$cat_id = (int) $_GET['cat_id'];

Open in new window


This will prevent SQL injection for any integer (or floating point numbers, use (float) for casting).

For strings, use the mysql_real_escape_string() function.

http://php.net/manual/en/function.mysql-real-escape-string.php

A better alternative is to use PDO or mysqli with prepared statements, or a similar framework.
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

Tackle projects and never again get stuck behind a technical roadblock.
Join Now