php variable in regex? - php

I have a variable $word and I'd like to match it in my select statement
somethig like this: "select * from table where column regex '[0-9]$word'"
but this doesnt work, so how can i put a variable in a regular exprssion?
Thank you

You must only put it correctly in SQL query, for example:
mysql_query("SELECT * FROM table WHERE column REGEXP 'prefix_".$word."'");
But you need to remember that the variable data needs to be properly escaped, i think that addslashes() would be enough.

You could try using preg_quote() to escape your string:
$sql = "select * from table where column regexp '[0-9]" . preg_quote($word) . "'";
There will be some issues because MySQL (assuming this is your DB) may have a completely different idea of which characters are special than PCRE.

Related

Can I use a variable directly inside the echo function without cause any incompatibility?

when I write a query for MySQL, usually use a form like this:
$column= "column_name";
$query = "SELECT * FROM table_name WHERE \"".$column."\"" = \"some_value\" ";
if I want to avoid using the \"". sequence for the variables, can I use this other form or there could be some compatibility issues or some other problem ?
$column= "column_name";
$query = "SELECT * FROM table_name WHERE \"$column\" = \"some_value\";
In both of these cases what you're doing is fine, but a few notes:
1) What you're doing in your first form is using the strings like string literals, which means you can/should use single quotation marks instead of double quotation marks, as they are parsed much faster.
$column = 'column_name';
$query = 'SELECT * FROM table_name WHERE ' . $column . ' = "some_value"';
What you're doing in the second example is also fine, it just depends on the reason you're trying to avoid using the escape character, but if you're just doing it for the sake of readability, what you have is fine.
Worth noting is that handling queries the way you're doing here is getting deprecated and you should take a look at PDO and inject your values that way.
Edit Per Comments Above - Removed " from around the column.
Yes, you can.
Strings delimited with double quotes are interpreted by the PHP parser.
to make sure, the variable is identified correctly, put it into curly brackets
Example
$variable = 1;
$array = array( 1,2 );
$object = new stdclass();
$object->member = 1;
$string = "You can basically put every kind of PHP variable into the string. This can be a simple variable {$variable}, an array {$array[0]} or an object member {$object->member} even object methods.";
If you want PHP to take the $variable literally without interpretation, put the string into single quotes.
Another method I really like to use for queries is the heredoc notation
$sqlQuery = <<< EOQ
SELECT
"field"
FROM
"table"
WHERE
"id" = '{$escapedValue}'
EOQ;
One more note:
In SQL you should delimit values with the single quote, and identifiers like table name and field names with double quotes (ANSI compatible) or the back tick ```

Syntax Help for Query

I'm trying to query my MySQL database to get information about a user. You submit a form on a previous page and then you go into the page and connect to the database and all that good stuff. I just have a quick question on syntax for the SELECT function for a query. I'm trying to say "select from tbl_name where the field first name concatenated with the field last name (with a space in between) equals the variable $user.
I figured with PHP I need to put slashes in front of the quotation marks. It doesn't seem to return any value though. Am I just using incorrect syntax?
$user=$mysqli->real_escape_string($_POST['user']);
$sql="SELECT * FROM tbl_name WHERE firstname.\" \".lastname='$user'";
You will have to use SQL's CONCAT() in your WHERE clause to join the firstname and lastname columns together:
SELECT
*
FROM
tbl_name
WHERE
CONCAT(firstname. ' ', lastname) = ?
Using your existing code in PHP (for copy+paste):
$sql = "SELECT * FROM tbl_name WHERE CONCAT(firstname, ' ', lastname) = '" . $user . "'";
* Also worth noting: since you're using MySQL you can legally-use single-quotes and/or double-quotes for strings in your queries (T-SQL is bound to single quotes for strings). Because of this, if you're wrapping your whole query with double-quotes in PHP you can use single-quotes inside your SQL-query instead of having to escape your double-quotes. This is more of a programmer's-preference tip, but one that may save you a quote-escaping headache one day =P
i think it is this what you are looking for??
$sql = 'SELECT * FROM '.$tbl_name .' WHERE CONCAT(firstname," ",lastname )='.$user.' ';

How can i check name with single quotes in SQL?

I have used below code for checking lastname(case sensitive) from DB.
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE 'ravi'
Its work fine. But, it does not work when the name like below, I passes this last name using php variable($lname).
SELECT * FROM $table_name WHERE BINARY LastName LIKE '$last_name'
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE 'O'Connor'
How can I resolve this?.
You need to escape all single quotes with a single quote:
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE 'O''Connor'
this should work.
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE 'O\'Connor'
and for php of course, you have mysql_escape or all PDO prepared statements that will take care of this automatically , given the LIKE value you use is bound to a php variable.
When you're building the query in your PHP script, use the addslashes function on the value you are searching for:
$query = "SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE '" . addslashes($name) . "'"
This will escape any characters that need it and will produce the result you are looking for.
Another solution is to use double quotes in the query instead of single quote:
SELECT * FROM BL12_anncurtis_existing_customers WHERE BINARY LastName LIKE "O'Connor"
but I think I prefer the first solution
you can write yourself a little program which uses regex for matching quotes, the program can validate and fix mistakes made by user.
You should be escaping your string with mysql_real_escape_string()
if you have magic_quotes_gpc turned on (which you should know is a bad idea). This means that strings gathered from $_GET, $_POST and $_COOKIES are escaped for you (i.e., "O'Connor" -> "O\'Connor").
Once you store the data, and subsequently retrieve it again, the string you get back from the database will not be automatically escaped for you. You'll get back "O'Connor". So, you will need to pass it through mysql_real_escape_string()
SELECT * FROM sometable where LastName LIKE '%''%'
WHERE BINARY LastName LIKE "O'Connor"
this works for me
I think that the \' may be better, but both work

What's wrong in this simple PHP SQL sentence?

i want to recober all the users with "blo" in their full name, for example: "Pablo"
I pass the "blo" parameter with user PHP parameter:
$q=mysql_query("select * From user Where fullName Like '%'".$_REQUEST['user']."'%'",$link );
something is wrong in the php SQL sentence, because when i try the sentence with the argument "blo" on my SQL database, i see that the SQL sentence is correct, because it returns me correct result, this is the sentence with the argument "blo" on it: select * From user Where fullName Like "%blo%"
i'm sure that the PHP is receiven the "blo" parameter correctly, then, it have to be a sintax error of the SQL sentence on the PHP.... but i can't find it
EDIT : OK!! the last sentence is solved, but now i have this new sentence with the same problem, it have a error but i dont know where
$query = sprintf("SELECT u.*
FROM USER u
WHERE u.fullName LIKE '%%%s%%' AND email NOT IN (select pp.fk_email2 from permission pp where pp.fk_email1='".mysql_escape($_REQUEST['mymail'])."') AND email NOT LIKE '".mysql_escape($_REQUEST['mymail'])."' ",
mysql_real_escape_string($_REQUEST['user']));
SQL requires single quotes to indicate a string for comparison, and the wildcard character (%) must be included inside of those single quotes. Double quotes are used for column and table aliasing only, if at all.
$query = sprintf("SELECT u.*
FROM USER u
WHERE u.fullName LIKE '%%%s%%'",
mysql_real_escape_string($_REQUEST['user']));
$q = mysql_query($query, $link);
Secondly, you're leaving yourself open to a SQL injection attack by not sanitizing the user request variable. Always use mysql_real_escape_string when dealing with strings being submitted to a MySQL database.
You have the quotes messed up. use this:
$q=mysql_query('SELECT *
FROM user
WHERE fullName LIKE "%' . $_REQUEST['user'] . '%"',$link );
BTW, this is bad practice. You are using un-escaped input in your query and are open to SQL injection.
It looks like your quotes are off.. try something like...
$q=mysql_query("select * From user Where fullName Like '%".$_REQUEST['user']."%'",$link);
Also, you will want to make sure that the incoming param is sql-escaped to prevent sql injection. I don't know php, but it's probably something similar to...
$q=mysql_query("select * From user Where fullName Like '%".mysql_escape($_REQUEST['user'])."%'",$link);
I think it must be ... Where fullname like '%" . $_REQUEST['user']."%'"...
with the % symbol inside the simple quotes.
#AndroidUser99: Change the query to --
$q = mysql_query("select * from user Where fullName like '%" . $_REQUEST['user'] . "%'", $link);
Update
I think we may need more code since none of the answers seem to be 'working'. Is the database link even being instantiated in $link? If there are errors what are they?

PHP escaping question

I have just read the following code but do not understand why there is " and also ' used. Thank you!
$sql='SELECT uid,name FROM users WHERE user="'.mysql_real_escape_string($_POST['login_name']).'" AND ..
There shouldn't be.
The "correct" $sql might look like this:
$sql="SELECT uid,name FROM users WHERE user='".mysql_real_escape_string($_POST['login_name'])."';
You use ' in SQL to say it's a string / literal.
I would suggest that you look into prepared statements, i don't trust mysql_real_escape_string nor mysql_very_real_seriously_this_is_the_real_escape_string, that php-syndrome is not to trust .
This is a PHP program to write an SQL query (and store it in a string).
The target SQL looks like this:
SELECT uid,name FROM users WHERE user="something" AND …
So in PHP terms:
$foo = 'SELECT uid,name FROM users WHERE user="something" AND …'
But you want to replace "something" with dynamic data. In this case the posted login_name — but made safe for MySQL.
$foo = 'SELECT uid,name FROM users WHERE user="' .
mysql_real_escape_string($_POST['login_name']) .
'" AND …'
A better approach is to use prepared statements.
The single quotes surround the SQL-statement ("SELECT..."), the double quote surround the data for the field "user" (though I'd use the quotes the other way around).
The query would look something like this (use single quotes):
SELECT uid FROM users WHERE user='snake'
To assign this query to the variable $sql, you'd have to enclose it in quotes, using double quotes this time, so PHP doesn't assume, the string would end before 'snake':
$sql = "SELECT uid FROM users WHERE user='snake'";
And as you won't always be asking for 'snake' statically, you exchange 'snake' with a dynamic name, exiting/entering the $sql-string by using double quotes again:
$sql = "SELECT uid FROM users WHERE user='" . $dynamic . "'";
If you only wanted one type of quotes, you'd have to escape the quotes that enclose the user-string.
the " will be literally included in the final mysql request so the request send to the mysql database will be:
SELECT uid,name FROM users WHERE user="loginname" AND ..
The single quotes are used to define your string in PHP. The double ones delimit your text field (login_name) in your SQL query.
This is done to avoid escaping the quotes of the query, if the same were used.
You can use single or double quotes for wrapping strings in php. However, there are differences.
With single quote strings, you cannot inline variables (eg: $a = 'hi $name'), nor can you escape characters (eg: $a = 'hi!\n$name').
Here is a nice summary: http://www.jonlee.ca/php-tidbit-single-quotes-vs-double-quotes/
Also on a side note.. Not sure if double quotes should be used for encasing strings in SQL. I do believe you should use single quotes in most DBs.
Looks like the single quotes are used for the PHP code what form the query and the double quotes are use for the query itself
More on Single/Double quotes
you can always echo out the $sql value to see how the Single/Double quotes look before executing the SQL against a DB.
something like:
$sql='SELECT uid,name FROM users WHERE
user="'.mysql_real_escape_string($_POST['login_name']).'";
// Print the SQL
echo $sql."<br />";

Categories