I have a PHP script with the following line:
$query = "SELECT * FROM products WHERE product_id='" . filter_var($_GET[id], FILTER_SANITIZE_NUMBER_INT) . "'";
Is this safe enough? How would you improve this code?
It is safe for that case, but for a more general approach, I'd rather use mysql_real_escape_string in conjunction with type casting:
$query = "SELECT * FROM products WHERE product_id='" . (int)mysql_real_escape_string($_GET['id']) . "'";
In the worst case, that will result in a 0 and will escape all malicious input also. mysql_real_escape_string can be used on all kinds of data to make it safe for queries, which makes it the most versatile of all escape/sanitation functions.
Without going as far as using prepared statements, you can use sprintf to create your SQL and to handle the type casting automatically:
$query = sprintf("SELECT * FROM products WHERE product_id = '%d'", mysql_real_escape_string($_GET['id']));
See the sprintf entry from the PHP manual for the syntax.
It gets even simpler if you use array_map to escape all $_GET and $_POST variables, then you can use them as is:
$_GET = array_map('mysql_real_escape_string', $_GET);
$_POST = array_map('mysql_real_escape_string', $_POST);
$query = sprintf("SELECT * FROM products WHERE product_id = '%d'", $_GET['id']);
I usually just use intval:
$product_id = intval($_GET['id']);
$query = "SELECT * FROM products WHERE product_id='" . $product_id . "'";
May be this works for you...!
$query=query("SELECT * FROM products WHERE product_id= ". escape_string($_GET['id']) . " ");
Related
I have a PHP file with my database configuration settings defined as constants, for example:
<?php
define(DB_HOST,"localhost");
define(DB_USERNAME,"root");
define(DB_PASSWORD,"password");
define(DB_NAME,"db_users");
define(DB_TABLE_1,"table_1");
define(DB_TABLE_2,"table_2);
?>
I obviously include the above file whenever I want to connect to my database..However, when I go to insert the table definition constants into the SQL query (see below) it doesn't seem to work. Do I need to properly escape the constant or concatenate it in some way?
$query = "SELECT users FROM DB_TABLE_1";
You'll have to use string concatenation (of any sort).
$query = "SELECT users FROM " . DB_TABLE_1;
constants will not interpolate into a string as variables can.
One hackish alternative is to use a variable function:
$const = 'constant';
$query = "SELECT users FROM {$const('DB_TABLE_1')}";
which'll execute the constant() function and return the constant's value, but that's generally not a good idea, if only for legibility's sake.
Just put it outside the quotes and it should work fine:
$query = "SELECT users FROM ".DB_TABLE_1;
I've found two ways.
1.-
define("VALUE1", "someValue");
$query = "SELECT * FROM TABLE WHERE `Column` /*=" . VALUE1 . "*/";
2.-
define("VALUE1", "someValue");
define("VALUE2", "otherValue");
$query = "INSERT INTO TABLE (`Column1`, `Column2`) VALUES (" . VALUE1 . ", " . VALUE2 . ")";
The backticks (``) I use because I'm using phpmyadmin, you might not need them.
I think this is easier:
$query = "SELECT users FROM '.DB_TABLE_1.'";
when using multiple tables:
$query = "SELECT TB_1.users, TB_2.names FROM '.TB_1.'
INNER JOIN '.TB_2.'
ON x=y";
Also, this is better:
define("DB_HOST","localhost");
mysql_real_escape_string adds slashes to the values in IN clause and hence no values are returned. How can I send array values that are escaped using mysql_real_escape_string() in IN clause?
Here is my code:
$names_array = array('dave','smith');
$names = mysql_real_escape_string("'". implode("', '", $names_array) ."'");
$sql = "SELECT * FROM user WHERE user_name IN ($names)";
$results = mysql_query($sql);
Query after mysql_real_escape_string changes like this:
SELECT * FROM user WHERE user_name IN (\'dave\', \'smith\')
I don't want these slashes here in IN clause. Also I don't want the values directly substituted in IN clause.
Thanks in Advance.
This might do it.
$names = "'". implode("', '", array_map('mysql_real_escape_string', $names_array)). "'";
Don't use mysql_real_escape_string; don't use the mysql_* functions directly at all; use ADODB or somesuch; don't concatenate your queries in this way, use placeholders (?) and prepared statements. Your code should look similar to this:
include('/path/to/adodb.inc.php');
$DB = NewADOConnection('mysql');
$DB->Connect($server, $user, $pwd, $db);
# M'soft style data retrieval with binds
$rs = $DB->Execute("select * from user where user_names in ?",array(array('dave','smith')));
while (!$rs->EOF) {
print_r($rs->fields);
$rs->MoveNext();
}
Example: The follwing query give me Quotes error in the field -> GET['email']
mysql_query(" select * from user_info where user_mail = '$_GET['email']' ")
You might want to escape the string first:
$_GET['email'] = mysql_real_escape_string($_GET['email']);
And then:
mysql_query(" select * from user_info where user_mail = '" . $_GET['email'] . "' ");
The dots put the strings together.
Use accolades like this.
mysql_query(" select * from user_info where user_mail = '{$_GET['email']}' ")
Also, make sure to escape your user input. Your current setup looks like it is vulnerable to SQL injection. Use http://php.net/manual/en/function.mysql-real-escape-string.php to clean up your user input (like $_GET values)
It's not really an answer to your question, but I'd strongly advise you to use PDO or mysqli prepared statements. Thus, your original problem -- the escaping parameter strings -- will be automatically taken care of.
If you do not want to follow this advice, do this:
$email = mysql_real_escape_string($_GET['email']);
mysql_query("select * from user_info where user_mail = '$email';");
You don't need quotation marks for associative array field names if you are already inside a doubly-quoted string:
$str = "Hello $_GET[email].";
Use it this way:
$SQL = "SELECT * FROM user_info WHERE user_mail = '".$_GET['email']."'";
mysql_query($SQL);
But I strongly advice to take some security actions with $_GET['email'], like this:
$email = mysql_real_escape_string($_GET['email']);
$SQL = "SELECT * FROM user_info WHERE user_mail = '".$email."'";
mysql_query($SQL);
Is this the right way to use mysql_real_escape_string? I was using $GET but a friend told me to make it safer with real_escape_string:
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = $id") or die("err0r");
if(!$result) mysql_real_escape_string($id); {
No, you normally use mysql_real_escape_string to prepare variables for use in a query, but in your case:
you already use intval;
you use it in the wrong place.
You don't need it in your example.
No. That is entirely wrong, and I can't quite understand what you're intending the call to do.
The purpose of mysql_real_escape_string is to avoid SQL injection, which is one of the biggest security risks in a website. It stops your users giving input that manipulates the SQL in evil ways. For instance:
$sql = "SELECT FROM users WHERE username = '" . $_GET['username'] . "'";
If I put lonesomeday' or 'a' = 'a into $_GET['username'], your query becomes
SELECT FROM users WHERE username = 'lonesomeday' or 'a' = 'a'
and obviously arbitrary SQL could then be executed. mysql_real_escape_string escapes unsafe characters (such as ' in that example), so that they can't be used in this way.
$sql = "SELECT FROM users WHERE username = '" . mysql_real_escape_string($_GET['username']) . "'";
// SELECT FROM users WHERE username = 'lonesomeday\' or \'a\' = \'a'
The quotes are now escaped. so the query can't be manipulated into doing evil things.
With all that said, in this case, intval does all you need. It also ensures that nothing that is not an integer can be in $id, so your code is safe here from SQL injection.
NO, you need to escape before quering
$id = intval($_GET['id']);
$result = mysql_query("SELECT *
FROM products
WHERE id = '" . mysql_real_escape_string($id) . "'") or die("err0r");
if(!$result) {
}
Use:
$query = sprintf("SELECT *
FROM products
WHERE id = %d",
intval($_GET['id']));
$result = mysql_query($query) or die("err0r");
You use mysql_real_escape_string before the value is used in the query, otherwise you're not handling the SQL injection attack.
you want to escape it before you stick it in a query (Before it interacts with DB so you don't get injections).
// check if your $_GET is not empty otherwise you
// will run into "undefined variable"
if(!empty($_GET['id'])){
$id = intval($_GET['id']);
// to simplify you can escape here,
// or to be a bit more complex, you can escape in the query line.
$id = mysql_real_escape_string($id);
$result = mysql_query("SELECT *
FROM products
WHERE id = '$id'") or die("err0r");
}
else
print 'No ID';
i have a little problem with a very simple query ,
when i hard code the values in the query its working , but when i use a PHP variable nothing is retrieved , i over check a lot of things including the query , the database
it worth saying that i'm getting the variable from a form by POST and also checked that i'm getting them but when i use them in a query they jst dont work :S
here's my code ..PLZ what am i doing wrong ?!!!!!!!!!!!
<?php
$email = $_POST ['emailEnter'] ;
$password = $_POST ['passwordEnter'];
$connection = mysql_connect('localhost','root','') ;
$db_selected = mysql_select_db("lab5" , $connection) ;
$query = 'select * From user where email="$email" and password="$password" ' ;
$result = mysql_query ($query , $connection);
while($row=mysql_fetch_array($result))
{
echo $row['name'];
}
mysql_close($connection);
?>
You use single quotes in the query variable. Single quotes does not substitute variables - so it looks for literal string $email not the variable email. Either use double quotes or even better use something like PDO which would do the work for you.
You should also sanitize your inputs from SQL/XSS vulnerabilities.
The basic debugging steps are 1. adding
if (!$result) echo "Error: ".mysql_error();
to see any errors from the SQL query and 2. outputting
echo "Query: $query";
to see what the variables contain. One of these will point you to the problem.
Also, your query is vulnerable to SQL injection. You should add a
$email = mysql_real_escape_string($email);
$password = mysql_real_escape_string($password );
after fetching the values from the POST array.
Your error probably resides in the fact that you don’t escape your parameters.
While you are at it, use MySQLi or PDO (maybe even some prepared statements)
Someone mentioned your use of single-quotes, that’s the real error, my bad.
But my advice still stands. Having used prepared statements, you wouldn’t have fell for that mistake
try
$query = 'select * From user where email="' . $email . '" and password="'. $password . '" ' ;
or
$query = "select * From user where email='$email' and password='$password'" ;
Try this instead:
$query = "select * From user where email='" . $email . "' and password='" . $password . "';
Then immediately change that to this instead:
$query = "select * From user where email='" . mysql_real_escape_string($email) . "' and password='" . mysql_real_escape_string($password) . "';
Try
$query = "SELECT * FROM user WHERE email = '".$email."' AND password = '".$password."'";
You've confused the single and double quotes
You have:
$query = 'select * From user where email="$email" and password="$password" ' ;
You want:
$query = "select * From user where email='$email' and password='$password' " ;
Single quotes evaluate to whats literally inside. Double quotes will parse for variables inside. Theres also a curly brace {$variable} syntax you can use.
Suggestions from other posters for using mysql_real_escape or using newer mysqli or PDO are important as well. At the very least use mysql_real_escape on parameters that come from user input.
the problem is the way you are quoting the variables. Suppose that $email= 'some#gmail.com' and $password= 'securenot'.
what we want is the final interpreted string to be the following
select * from user where email='some#gmail.com' and password='securenot'
to achieve this we simply replace the some#gmail.com for $email and securenot for $password and get the following:
select * from user where email='$email' and password='$password'.
and then in php code ...
$query = "select * from user where email='$email' and password='$password'";
hope that is of some help
mysql_fetch_assoc() for associative array. You cannot use normal array as assoc array.
while($row=mysql_fetch_assoc($result))
{
echo $row['name'];
}