Let's assume we want to give an input so that the program understands a variable we use. For example:
$name=$_POST['name'];
$p='...';
$sqlLogin= "SELECT user_id FROM user WHERE username=' ".$name." ' ";
if the input is {$p} , then the variable is not printed , instead the result is:
SELECT user_id FROM user WHERE username='{$p}'
Is there a way for the program to understand {$p} as a variable (through input), like it does
when we write
$sqlLogin= "SELECT user_id FROM user WHERE username='{$p}'";
Just to prove the concept here:
$name = '{$p}';
$p= 'MYVALUE';
echo eval("return \"".eval("return 'SELECT * FROM tblname WHERE username =\'$name\'';").'";');
Result:
SELECT * FROM tblname WHERE username ='MYVALUE'
But try to avoid the use of eval();
Have a nice day;
You will need to use the eval() function because the variable is a string, so the code is treating it as such, but you want the string to be ran as code.
eval("$sqlLogin = \"SELECT user_id FROM user WHERE username='{$p}'\"")
Related
I'm trying to write a PHP string to create an SQL statement which uses a variable for a field name after the WHERE clause. The problem is that it doesn't use the variable name, I'm not good with PHP so not sure if it's my string concatenation or something else... any help would be appreciated! I'm using PHP 5.5 with mysql, as mysqli isn't available with my current host.
echo $sql_subject;
$sqlString2 = "SELECT * FROM tableName WHERE ". $sql_subject . " = '$set'";
However it keeps outputting:
S
SELECT * FROM tableName WHERE '' = '1'
I know the $sql_subject has a value because it's printing above the SQL output... I'd like it to say:
SELECT * FROM tableName WHERE S = '1'
Thanks
I am allowing people to input either their username, account number or email address before typing their password, so i need to compare their input against 3 fields in my table but i am not getting any results.
i first tried this ...
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE username='$thisuser' or accnum='$thisuser' or email='$thisuser'");
then i read on here that brackets should be placed around OR statements, so tried this ...
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE (username='$thisuser' or accnum='$thisuser' or email='$thisuser')");
but neither work, can someone help please
just for comparison, this does work when i type in the username value ...
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE username='$thisuser'");
What is the datatype of accnum? Are you sure it is varchar?
If accnum is of type numeric then try
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE (username='$thisuser' or accnum=$thisuser or email='$thisuser')");
Seems no problem. Please check '$thisuser' has value. Try printing the sql statement.
You may try running query directly on database.
I also think first check the value of $thisuser, and then try below query
$result = mysqli_query($con,"SELECT * FROM useraccounts WHERE (username='".$thisuser."' or accnum='".$thisuser."' or email='".$thisuser."')");
Rathere then using at server side if it done at client side in js file by checking it emailid or username oraccount number according to that u can pass value
mysql_query("SELECT * FROM foo WHERE id ='$foo' OR id = '$foo2");
This doesn't work.
Basically, I want to be able to select it where the id is one variable's value OR another one's.
Thanks.
EDIT: The ID column is numerical.
As others have said and you confirmed, the problem is that you are using string literals to compare to a numeric column. To have it work, the query should look like
mysql_query("SELECT * FROM foo WHERE id =$foo OR id = $foo2");
However, this solution has very very bad code smell!
First off, this is why IN exists: to be able to write
mysql_query("SELECT * FROM foo WHERE id IN ($foo, $foo2)");
And second, are you injecting unescaped strings into your query? If you are, your code is vulnerable to sql injection! Escape and quote your variables to be safe, like this (in the general case):
$query = sprintf("SELECT * FROM foo WHERE id IN ('%s', '%s')",
mysql_real_escape_string($foo),
mysql_real_escape_string($foo2));
mysql_query($query);
or alternatively like this, since in this specific scenario you know we 're talking about integer values:
$query = sprintf("SELECT * FROM foo WHERE id IN (%s, %s)",
intval($foo), intval($foo2));
mysql_query($query);
Footnote: I am aware that when using sprintf like this, one could also handle integer values by just using %d instead if %s as the format specifier. However, I believe that proving you are correctly escaping variables should be possible by just looking at one place (the parameter list) instead of multiple places (did I use intval on the variable? or maybe I did not, but I 'm using %d in the format string so I 'm still OK?). It may sound counter-intuitive, but it's more robust in the face of modifications.
I think you forgot the last ' character
mysql_query("SELECT * FROM foo WHERE id ='$foo' OR id = '$foo2'");
but because the id column is numerical, you should use:
mysql_query("SELECT * FROM foo WHERE id = $foo OR id = $foo2");
Try this:
mysql_query(sprintf("SELECT * FROM foo WHERE id = %s OR id = %s", $foo, $foo2));
I recommend you use mysql_error() for get mysql errors(if exists).
mysql_query( .. ) or die('Erro:'.mysql_error());
the mysql_error returns the last error occurred in mysql.
When is the correct time to use mysql_real_escape_string?
Should I be using it when I use isset(mysql_escape_string($_GET['param'])),
Should I be using it when I use $foo = mysql_real_escape_string($_GET['bar']);
Thanks
You need to call this function when building SQL queries with string literals.
You should not call it anywhere else.
The point of calling this function is to prevent you from executing SQL like SELECT * FROM Students WHERE Name = 'Robert'); DROP TABLE Students;--'.
mysql_real_escape_string will escape the ' character so that the evil string is treated entirely as a string.
You should use it whenever you don't trust the data you are inserting in a mysql query to prevent sql injections. For example all user forms data.
In your first example: no.
Second example: yes, if you are going to use the $foo variable in a query.
You should use it whenever you are inserting data into a database query (POST/GET data), but not if you just need to check the data.
You use mysql_real_escape_string whenever you have input from a user that you want to use in a query.
Here's how to use it:
$user = mysql_real_escape_string('$_GET['user']);
$password = MD5($user.$_GET['password']);
$query = "SELECT * FROM users WHERE user = '$user' AND password = '$password' ";
//the quotes are vital !! ^ ^ or you will not be safe!
Here's example code that doesn't work:
Broken code
$user = mysql_real_escape_string('$_GET['user']);
$password = MD5($user.$_GET['password']);
$query = "SELECT * FROM users WHERE user = $user AND password = '$password' ";
In the example I can login into your system by entering any password whatsoever and
user or (1=1) --. This will make the query to read:
SELECT * FROM users WHERE user = user or (1=1) -- AND password = '$password
And will approve all logins because the password never gets checked.
When using mysql_query, you can only ever execute one SQL-statement at a time, so:
$query = "SELECT * FROM a; DELETE FROM a WHERE (1=1)"
mysql_query($query);
Will result in an error, because cannot be a part after the ;.
This code however will work:
Danger
$query = "SELECT * FROM a; DELETE FROM a WHERE (1=1)"
mysqli_query($query);
Because the improved mysqli_query does allow two or more statements to be executed in one go.
Alt A below is a statement from a php-mysql tutorial. It works as it should.
I found the id-value rather obfuscated and tested alt B. This also worked!
What is the point with the id-value of alt A?
MySQL 5.0.51, PHP 5.2.6
// Alt A :
$sql = "SELECT * FROM example WHERE id = '".$q."'";
// Alt B :
$sql = "SELECT * FROM example WHERE id = $q";
This are just two different approaches to building a string from static and variable data.
Alternative A uses concatenation, or the joining of string and variable tokens using the concatenation operator.
Alternative B uses variable expansion, wherein the variables inside a double-quote-delimited string are expanded to their values at evaluation time.
Neither is necessarily better or preferred, but if you have to have single-quote-delimited strings, for example, then you would need to use alternative A.
Of course, neither of these is preferable to building SQL queries with bound parameters, as not doing so leaves you vulnerable to SQL injection attacks.
Theres two reasons to use the example in 'Alt A'. First is if the string is enclosed in single quotes '', the variable's name will be used in the string instead of it's value.
$id = 7;
'SELECT * FROM table WHERE id = $id' //works out to: WHERE id = $id
"SELECT * FROM table WHERE id = $id" //works out to: WHERE id = 7
Secondly, it's useful to combine strings with the results of a function call.
"SELECT * FROM table WHERE id = '".getPrimaryId()."'"
Outside of what has already been said I've found it best practice, if I'm writing a query, to write it as so:
$sql = "SELECT * FROM table WHERE uid=" . $uid . " LIMIT 1";
The reason for writing SQL like this is that 1. MySQL query doesn't have to parse the PHP variables in the Query and 2 you now easily read and manage the query.
When PHP communicates with MySQL, it is actually (in essence) two languages communicating with each other. This means that a string will be processed by the first language before being sent to the other. It also means that it is important to think in terms of the receiving language
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = $q";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = some_name.
In this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '$q'";<br/>
and this case:
$q = 'some_name';<br/>
$query = "SELECT * FROM exempel WHERE id = '".$q."'";<br/>
you are telling MySQL to
"SELECT * FROM example1 WHERE id = 'some_name'.
The first example should cause an error as some_name is not a valid part of a MySQL query (in that context). On the other hand, the next two will work fine, because MySQL will look for the String "some_name".
You can also do this:
$sql="SELECT * FROM exempel WHERE id = {$q}";
which is useful for setting off things like:
$sql="SELECT * FROM exempel WHERE id = {$row[id]}";
in 'alt B', $q must be an int or float or other numeric
in 'alt A', $q can be anything a string, int, etc.
The single quote makes that possible. It's just hard to see sometimes if you are looking at it for the first time.