Why do this..
$fruit_type = "banana";
mysql_real_escape_string($fruit_type);
$query = "SELECT * FROM posts WHERE fruit = " . $fruit_type . ";
when you can do this..
$fruit_type = "banana";
mysql_real_escape_string($fruit_type);
$query = "SELECT * FROM posts WHERE fruit = $fruit_type;
I know that integers should be encapsulated in single quotes but is it fine to add a variable that contains a string directly?
Adding a string directly, without quotes (and escaped quotes within the value) will not work if that is your question.
The following will work with integers, provided you are matching on an number field, but it will not work with strings:
$query = "SELECT * FROM posts WHERE fruit = $fruit_type";
To match strings, you must enclose them within single quotes, and escape single quotes occurring within the value. The following will not escape quotes contained within the passed variable:
$query = "SELECT * FROM posts WHERE fruit = '$fruit_type'";
At the very least, you should do this:
$query = "SELECT * FROM posts WHERE fruit = " . mysql_real_escape_string($fruit_type);
And at the first opportunity, read about these:
http://php.net/manual/en/pdo.prepared-statements.php
Typically, no. The reason is just this:
$fruit_type = "; DELETE FROM posts;";
There's nothing inherently wrong with the syntax, it's your approach in general. You want to make sure that all user input strings are escaped.
I think you missed the quotes for the string.
$query = "SELECT * FROM posts WHERE fruit = '$fruit_type';
Also, its a good practice to use bind variables in SQL in order to avoid DB query parsing
To late but it will help others
`
$table ="table_Name";
$idx="value";
$sql="SELECT * FROM $table WHERE row_name= '$idx'";
`
execute your query .
Related
I need to write my php variables correctly.
$query2 = mysqli_query($con,"SELECT * FROM palettes LIMIT '$starting_number, $palettes_per_page'");
I don't think you want single quotes on your LIMIT parameters. One way is to use . to concatenate strings.
Since $starting_number and $palettes_per_page are integers, you do not need to escape them. If they were strings, wrap them in mysqli_real_escape_string or mysqli_escape_string to escape special characters.
$query2 = mysqli_query( $con,
"SELECT * FROM palettes LIMIT " .
$starting_number .
"," .
$palettes_per_page );
Just remove the single quote, because double quote can read variable's value
$query2 = mysqli_query($con,"SELECT * FROM palettes LIMIT $starting_number, $palettes_per_page");
Hope this works for you
You could use parameterized queries which also prevent any need to use mysqli_real_escape_string
$stmt = $conn->prepare("SELECT * FROM palettes LIMIT ?, ?'");
$stmt->bind_param("ii", $starting_number, $palettes_per_page);
$stmt->execute();
This script is supposed to retrieve the CustomerID for the Customer_First_Name and Customer_Last_Name that has been entered into a form.
$query = "SELECT CustomerID FROM customer WHERE Customer_First_Name = `.$db_customer_first_name.` AND Customer_Last_Name = `.$db_customer_last_name.`";
$result = mysql_query($query)
or die(mysql_error());
echo $result;
echo $query;
when the script runs I get this error:
Unknown column '.Christopher.' in 'where clause'
the query is never printed on the screen.
any help is appreciated.
Your quotes are bad use ' instead of the tick `
You have to use single quotes for strings. Try again:
$query = "SELECT CustomerID FROM customer WHERE Customer_First_Name = '".$db_customer_first_name."' AND Customer_Last_Name = '".$db_customer_last_name."'";
This should work:
$query = "SELECT CustomerID FROM customer WHERE Customer_First_Name = '$db_customer_first_name' AND Customer_Last_Name = '$db_customer_last_name'";
You need to use normal single quotes for values. Also you don't need to break the string if you're using double quotes - variables are detected within the string.
Make sure you're also correctly escaping your strings for mysql to prevent injection.
Better still, look at moving to mysqli and using prepared statements.
Use ' instead of remove `
$query = "SELECT CustomerID FROM customer WHERE Customer_First_Name = '".$db_customer_first_name."' AND Customer_Last_Name = '".$db_customer_last_name."'";
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");
I have 2 values that I'm suppling my script - I want to search for any one of those datas. How do I write my query like this:
SELECT * FROM table WHERE id = '".$id."' or "name='".$name."';
my problem is escaping the quotes in the query.
Any help will be appreciated.
There are a few ways to do it, a lot of them frowned on but generally I would stick to using MySQLi and using the
mysqli_real_escape_string($id)
function or in OOP
$mysqli = new mysqli('host', 'user', 'pass', 'database');
$id = $mysqli -> real_escape_string($id);
$name = $mysqli -> real_escape_string($name);
$results = $mysqli -> query("SELECT * FROM table WHERE id = '{$id}' or "name='{$name}'");
You may use curly brackets to avoid confusion with escaping characters as follows:
$query = "SELECT * FROM table WHERE id = '{$id}' or name = '{$name}' ";
You may also consider using wildcards such as %$letter% to search for word anywhere in the name field as:
$query = "SELECT * FROM table WHERE id = '{$id}' or name LIKE '%{$name}%' ";
SUGGESTTION:
You should always use id fields as integer for better performance.
Use this fancy function, mayhaps? The examples have what you're looking for.
You've got an extra quote; if you want to stick with your original code (not recommended), try something like this:
$query = "SELECT * FROM table WHERE id = '".$id."' or name='".$name."'";
But really you should be using parameterised queries so that you avoid possible SQL injection security issues!
Write it as:
$name = mysql_real_escape_string($name);
$id = mysql_real_escape_string($id);
$query = "SELECT * FROM table WHERE id = '$id' or name= '$name' ";
Because you started with double quotes the single quotes are part of the query and the $vars are expanded.
Should numbers from user input be quoted in MySQL queries to help avoid SQL injection attacks?
Say i have a form on a page asking for someone's age. They enter their age and hit submit. The following php code deals with the form submission: (age is an int field in the db table.)
$Number = mysqli_real_escape_string($dbc, $_POST["age"]);
$Query = "INSERT INTO details (age) VALUES ($Number)";
$Result = mysqli_query($dbc, $Query);
Instead of this, is there anything to be gained to enclosing the user input in single quotes, even though it is not a string? Like this:
...
$Query = "INSERT INTO details (age) VALUES ('$Number')"; <-- quotes
...
What about performing a SELECT? Is this:
$ID = mysqli_real_escape_string($dbc, $_POST["id"]);
$Query = "SELECT * FROM users WHERE id = '$ID'";
$Result = mysqli_query($dbc, $Query);
better than:
$ID = mysqli_real_escape_string($dbc, $_POST["id"]);
$Query = "SELECT * FROM users WHERE id = $ID"; <-- no quotes
$Result = mysqli_query($dbc, $Query);
NOTE: I am aware of prepared statements and usually use them over string concatenation but this is legacy code i'm dealing with. I want to secure it as best as i can.
If you add numbers, use the intval/floatval functions, don't use mysql_real_escape_string for those.
For everything you use mysql_real_escape_string for, you must use quotes, example:
$input = "foo'bar";
$input = mysql_real_escape_string($input);
//foo\'bar
mysql_query("SELECT $input");
//SELECT foo\'bar
//which is still an SQL syntax error.
You really shoud use sprintf, even if in legacy code it takes 2 mins to modify and is in my opinion totally worth the time.
Shamelessly ripped from php.net:
// Formulate Query
// This is the best way to perform an SQL query
// For more examples, see mysql_real_escape_string()
$query = sprintf("SELECT firstname, lastname, address, age FROM friends
WHERE firstname='%s' AND lastname='%s'",
mysql_real_escape_string($firstname),
mysql_real_escape_string($lastname));
// Perform Query
$result = mysql_query($query);
Your query is now pretty much safe from being passed the wrong types to it's fields and unescaped caracters.
You SHOULD use the PHP filters, and filter for numbers - even for ranges, regular expressions; with default values, NULL on failure, etc.
http://hu.php.net/manual/en/ref.filter.php
if the values come from a request variable, e.g. $_POST, see:
http://hu.php.net/manual/en/function.filter-input.php