Checking function with spaces in it in php - php

I am using this query
"SELECT * FROM items WHERE itemname LIKE '%$name%'"
If $name="alex", then the query returns the correct information. But if $name="alex " with trailing whitespace, then no results are returned.
If $name="alex dude", then this is valid, but $name="alex dude " is not. I only want to remove whitespace at the end of the string.
I have written a function to clear out spaces at the end of name. This is the function.
function checkname($dataname)
{
$func_name ="";
$checker = substr($dataname, -1);
if($checker == " ")
{
$func_name = substr_replace($dataname, "", -1)
function checkname($dataname);
}
else
{
$dataname = $func_name;
}
return $dataname;
}
This gives me a PHP Parse error:
syntax error, unexpected 'function' (T_FUNCTION) in C:\inetpub\vhosts\httpdocs\compare.php on line 176`.
I don't understand why recursively calling a function is giving me an error.
Can you guys help out with this? Is there a better solution or better SQL query than I am using?

There are two reasons you'll get errors. The first reason, and the reason you're seeing the message:
Parse error: syntax error, unexpected 'function'
is that you're missing a semicolon after $func_name = substr_replace($dataname, "", -1).
function is unexpected because you haven't terminated the previous line.
If you fix that, you'll still get an error, because you're using function checkname($dataname); to do the recursive call, when it should be return checkname($dataname); If you use it the way you have it, you'll get a cannot redeclare function error.
If you want it to work recursively, it can be simplified to
function checkname($dataname) {
if (substr($dataname, -1) == " ") {
return checkname(substr_replace($dataname, "", -1));
}
return $dataname;
}
But as others have said, this does basically the same thing as trim() or rtrim().

You can do direcly in sql
"SELECT * FROM items WHERE itemname LIKE concat('%', trim('$name'), '%')"
or rtrim
"SELECT * FROM items WHERE itemname LIKE concat('%', rtrim('$name'), '%')"

You can use trim, it's PHP native function stripping whitespace from the beginning and end of a string.
$trimmed = trim(' my string ');
echo $trimmed; // 'my string'
You can find more informations regarding it in the documentation.
By default, it will remove ordinary space, tab, new line, carriage return, NUL-byte and vertical tabs.
You can also control which characters are removed at the start and end of the string by using a second parameter to the trim function as specified in the documentation.

Try
SELECT * FROM items WHERE itemname LIKE '%". trim($dataname) ."%'"
trim($string) Strip whitespace (or other characters) from the beginning and end of a string

I'm using str_replace function
$name="a l e x" ;
$abcd = str_replace (" ", "", $name);
$res=mysql_query("SELECT * FROM `name` WHERE `name` LIKE '%$abcd%'") or die(mysql_error());
while($x=mysql_fetch_array($res))
{
echo $x['name']."<br>";
}
str_replace (" ", "", $name) helps to your problem
or by using sql
"SELECT * FROM `name` WHERE `name` LIKE '%".str_replace (" ", "", $name)."%'"
and it removes all your white spaces.

Related

PHP query not working with variable

In my page I have this code with echo's.
<?php
include("../config.php");
$q = mysql_query("SELECT propertyaddress FROM propertydetail WHERE active='yes' and leasedatefrom='".date("m-d-Y", strtotime('+1 months'))."'");
$res = mysql_fetch_array($q);
echo "<br/>pdetail=".$pdetail=trim($res['propertyaddress']);
echo $query="SELECT * FROM tenantmaster WHERE propertyaddress like '".$pdetail."'";
//echo $query="SELECT * FROM tenantmaster ";
//echo $query="SELECT * FROM tenantmaster WHERE propertyaddress = '1934 Heron Ave Unit D Schaumburg IL 60193'";
$resultdb = mysql_query($query);
if (!$resultdb) {
die('Invalid query: ' . mysql_error());
}
else{
echo "<br/>right query";
}
echo "<br/>num of row===".mysql_num_rows($resultdb);
$rowt = mysql_fetch_array($resultdb);
echo "<br/>row===".$rowt['name'];
exit;
?>
config.php
<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "gms_estate";
/*
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "gms_estate";
*/
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
And problem is my first query $q is working but query $query is also working but mysql_num_rows($resultdb) is not working and display 0 rows but, when I run echo query to database it's displaying 1 row. Why?
I tried $res['propertyaddress'] variable with trim() but not any success.
But when I use 1934 Heron Ave Unit D Schaumburg IL 60193 (that's my variable value) instead of $res['propertyaddress'] then it's working.
So, when I give value of variable directly then it's working but when I give variable then not. Why?
A common problem with comparing text entry from multi-line fields is that you probably have a "newline" or "tab" in the results from the first query, but that is not in the second query. (Other gotchas are "non-breaking space").
As you are echoing in HTML you won't see those in the output (so copying and pasting works), but they will be used in the query (so direct input fails). Try "View Source" (which shows newlines) or run in command line as that might give you more clues.
For now, strip out anything other than alpha numeric and spaces using preg_replace
$pdetail = trim( preg_replace("/[^0-9a-zA-Z ]/", "", $res['propertyaddress']) );
Eventually you'll want to adjust that to cover all your use cases, or of you find it's a "newline" just remove those - but you need to find what's different.
And, as per comments: check out mysqli / PDO parameterized queries. If the original address contained a single quote mark, that would also fail (with unknown results). It's a pain first off, but it'll save you a lot later on, makes your code easier to read and also will get more help here on SO (as your code is easier to read).
http://php.net/manual/en/pdo.prepared-statements.php
<?php
include("../config.php");
$connect = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_database", $mysql_user, $mysql_password);
$q = "SELECT propertyaddress FROM propertydetail WHERE active='yes' and leasedatefrom='".date("m-d-Y", strtotime('+1 months'))."'";
$result = $connect->prepare($q);
$status = $result->execute();
$res = $result->fetch(PDO::FETCH_ASSOC);
$pdetail = $res["propertyaddress"];
$q = "SELECT * FROM tenantmaster WHERE propertyaddress = ".$connect->quote($pdetail);
/* or
$q = "SELECT * FROM tenantmaster WHERE propertyaddress like ".$connect->quote($pdetail);
*/
$result = $connect->prepare($q);
$status = $result->execute();
echo "<br/>num of row===".$result->rowCount();
if (($status) && ($result->rowCount() > 0))
{
$res = $result->fetch(PDO::FETCH_ASSOC);
echo "<br/>row===".$res['name'];
}
$connect = null;
?>
First of all it is recommended to use the mysqli along with prepared statement since it will avoid the SQL Injections that will occur. Now your code is purely injectable and it can be rectified with the help of mysqli along with prepared statements or with the help of PDO.
Mysqli with Prepared Statement: http://php.net/manual/en/mysqli.prepare.php
PDO: http://php.net/manual/en/book.pdo.php
PDO with Prepared: http://php.net/manual/en/pdo.prepare.php
Explanations
As per the usage of trim() in your variable you will be getting the strategy as per this alone.
trim- Strip whitespace (or other characters) from the beginning and end of a string
Description: This function returns a string with whitespace stripped from the beginning and end of str. Without the second parameter, trim() will strip these characters:
" " (ASCII 32 (0x20)), an ordinary space.
"\t" (ASCII 9 (0x09)), a tab.
"\n" (ASCII 10 (0x0A)), a new line (line feed).
"\r" (ASCII 13 (0x0D)), a carriage return.
"\0" (ASCII 0 (0x00)), the NUL-byte.
"\x0B" (ASCII 11 (0x0B)), a vertical tab.
Note:
But trim() does not remove the white space which is present at the middle of the string that is given.
Example:
trim() trims characters from the beginning and end of a string, it may be confusing when characters are (or are not) removed from the middle. trim('abc', 'bad') removes both 'a' and 'b' because it trims 'a' thus moving 'b' to the beginning to also be trimmed. So, this is why it "works" whereas trim('abc', 'b') seemingly does not.
Scenario: Hence in order to remove all teh white space that is present in the string you have to use the following.
You have to first remove all the character other that alpha numeric and white spaces with the help of preg_replace() function.
After replacing all the above mentioned items you have to then trim upon the variable so that it will remove all the white spaces that has been present and hence your string will look as the string which you give in hard code or directly.
3. You can directly adopt the method by strong the trimmed value into a variable and then echo it.
preg_match - Perform a regular expression match
Description: Searches subject for a match to the regular expression given in pattern.
Return Values: preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.
Solution to your Problem
But when I use 1934 Heron Ave Unit D Schaumburg IL 60193 (that's my variable value) instead of $res['propertyaddress'] then it's working.
Reason: This Error occurs when you printing the values directly from the Database.
If you have used any editor it will store the content directly to the DB as HTML tags alone.
Hence in order remove the HTML tags you have first store the DB value into a variable by replacing all the values and then you have to display it.
If you echo it directly you will not be seeing the HTML tags but if you view it by using CTRL+U you will be seeing it in the seeing it and it is not recommended. Hence you have to remove or strip of the parameters and then trim it.
Query:
preg_replace("/(\W)+/", "", $word_to_undergo);
Note: \W - Anything that isn't a letter, number or underscore.
So, in terms of Unicode character classes, \W is equivalent to every character that are not in the L or N character classes and that aren't the underscore character.
Alternative Solution:
To remove just put a plain space into your character class:
Query:
$needed_text = preg_replace("/[^A-Za-z0-9 ]/", "", $word_to_undergo);
Along with the above Solution you have to preform the trim so that it produces a perfect string as per your choice and it will match up with the query and produce the result.
As per Suggestion One: It should be
$final_value = preg_replace("/(\W)+/", "", $word_to_undergo);
$final_value = preg_replace("/(\W)+/", "", $res['propertyaddress']);
As per Suggestion Two: It should be
$final_value = preg_replace("/[^A-Za-z0-9 ]/", "", $word_to_undergo);
$final_value = preg_replace("/[^A-Za-z0-9 ]/", "", $res['propertyaddress']);
Addition to the above solution you can try using like this to.
<?php
$display=trim($res['propertyaddress']);
echo $display;
?>
Instead
echo "<br/>pdetail=".$pdetail=trim($res['propertyaddress']);
Use
$pdetail=trim($res['propertyaddress']);
echo "<br/><pre>pdetail='".$pdetail."'</pre>";
And you will can see real variable value
Change your query from
echo $query="SELECT * FROM tenantmaster WHERE propertyaddress like '".$pdetail."'";
To
echo $query="SELECT * FROM tenantmaster WHERE propertyaddress like '%".$pdetail."'%";
Please try with this query. It will be helpful for getting your result
$query='SELECT * FROM tenantmaster WHERE propertyaddress like "'.$pdetail.'";
You are missing mysql_free_result($q); and mysql_free_result($query) to announce that you are finished with the query.
And do change to mysqli (or PDO).

trim function is giving unexpected values php

I have taken the following inputs
$file = 'D:/php/testapp/ta_bles.json';
$table = trim(end(explode("/", $file)), '.json');
but instead of giving ta_bles as the output it is giving ta_ble
can any one help me what is happening
but when i use the following logic it gave expected results
$table = str_replace('.json', '', end(explode("/", $file)));
The reason why it doesn't work as expected is because the second argument to trim() (and related functions) is used as a character set; so in the extreme example of "json.json" you will end up with an empty string because it trims each character separately.
You could compare such an operation to this:
preg_replace('/^[.json]+|[.json]+$/', '', $str);
To just get "tables" you should use pathinfo() instead of trying to roll your own:
$table = pathinfo('d:/php/testapp/tables.json', PATHINFO_FILENAME);

What does '\" actually mean in PHP Syntax?

I have a piece of code and i keep getting syntax errors for codes like thess :
$query ="SELECT * from `jos_menu` where `id` = ".'\".$parent.'\";
Now when i reformat it as :
$query ="SELECT * from `jos_menu` where `id` = ".$parent;
That is when i remove : '\"
it works fine. So i am just wondering, what does ('\") actually do ???
\ is the escape character. It means the next character should be taken literally, without care for its special meaning.
In PHP, you would generally see '\" inside of a string if the string were delimited with double quotes (and the developer just wanted a preceding single quote).
It works fine because you have a numeric value - so mysql automatically converts a string to a number for you. So you get 2 different queries (assuming that $parent = 42;:
SELECT * from `jos_menu` where `id` = 42
vs
SELECT * from `jos_menu` where `id` = "42"
It denotes escaped characters. The next character that appear after it, will be taken as its current form.
Your Query is incorrectly escaped
$query ="SELECT * from `jos_menu` where `id` = ".'\".$parent.'\";
//^ You mismatched the quotes from here
A correctly escaped query should be
$query ="SELECT * from `jos_menu` where `id` = \"$parent\"";
// ^ Note here " will printed as it is within the query
For example,
If $parent was 2, then the query would be
SELECT * from `jos_menu` where `id` = "2"
The only problem with
$query ="SELECT * from `jos_menu` where `id` = ".'\".$parent.'\";
Is that you missed a few ':
$query ="SELECT * from `jos_menu` where `id` = ".'\"'.$parent.'\"';
In PHP, a string can either be:
$var = 'This is a string';
Or
$var = "This is a string";
If you want to put " inside a string that you already started with ", you need tell PHP that you don't want your second " to end the string but use the character " as part of the string itself. This is what \" does. It tells PHP that Don't give the " character any special meaning; since normally if you started the string with ", the next " would end the string.
\ means remove any "special" meaning to the next character
This only works if the character after the \ would have had special meaning. Some examples:
Suppose we want to print Hello "World". I am a string!:
$var = "Hello "World". I am a string!";
In this example we will have errors. Since we started the string with ", the next " will close the string. So what PHP thinks:
" Start of string
Hello part of string variable.
" Hey, since I saw that the string was started with ", this must mean the end of it!
World" <-- Error
Stop processing and throw errors.
However, if we write:
$var = "Hello \"World\". I am a string!";
Now, PHP thinks:
" Start of string
Hello part of string variable
\ Ah, okay, the next character I should remove any special meaning
" Okay, this is immediately after \, so I just use it normally, as a ".
World part of string
\ Okay, the next character I will remove any special meaning
" This is now a normal "
. I am a string! - part of string variable.
" Ah! Since the string was started with ", this must be the ending.
; ends statement.
Hopefully this clarifies things for you.
A few things:
To denote the next character a literal, '\'' // outputs a single '
Special characters, \n newline, \t tab character etc
The back-slash escapes next charactor after it; in your example this would work:
$query = "SELECT * from jos_menu where id = ".$parent;
But so would this:
$query = "SELECT * from jos_menu where id = $parent";
When escaping quotations, it varies on the type of parenthesis used. With double parenthesis, you can include the variable right into the string, just be careful of accessing arrays by key:
$var = "This \"works\" ".$fine.".";
$var = "This 'also' works just $fine.";
$var = "This $will['fail'].";
$var = "However, $this[will] work and so ".$will['this'].".";
Same rules apply for single parenthesis.

Regexp and variable

I have this form, wich outputs some letters and a wordlength. But I've got some problems with getting a right output from my database.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$letters = mysql_real_escape_string($_POST['letters']);
$length = mysql_real_escape_string($_POST['length']);
echo "Letters: $letters";
echo "Lengte: $length";
$res=mysql_query("SELECT word FROM words WHERE word REGEXP '[$letters]{$length}' ")
or die ('Error: '.mysql_error ());
while ($row=mysql_fetch_array($res)){
echo $row['word'];
echo "<br />";
}
}
else {
echo "Foutje";
}
If I change $length to the integer that was inputted by the form my script works. Copy/pasting [$letters] 6 times works also. I guess there is a problem with quotes but I totaly can't figure out what it exactly is.
Can anyone see what I did wrong?
Thanks.
The {} are being interpreted by PHP as delimiters for the variable inside since you are using a double-quoted string. Change your quoting around with concatenation:
$res=mysql_query("SELECT word FROM words WHERE word REGEXP '[" . $letters . "]{" . $length ."}'")
Or double up the {} inside a double-quoted string so the outer pair are interpreted as literals.
$res=mysql_query("SELECT word FROM words WHERE word REGEXP '[$letters]{{$length}}' ")
Note, you should also verify that $length contains a positive integer.
if (!ctype_digit($length)) {
// error - length must be an int
}
try doing this:
res=mysql_query("SELECT word FROM words WHERE word REGEXP '[".$letters."]{".$length."}' ")
I have a hunch that the $ is getting intepreted as part of the regex

too few arguments sprintf

I have done this many times before, to re-use a value passed into the sprintf() function. But this code is returning a "Warning: sprintf() [function.sprintf]: Too few arguments in..." message.
Here is the code:
$search_clause = sprintf(" (msgBody LIKE %%%1$s%% OR msgSubject LIKE '%%%1$s%%' ) ", mysql_real_escape_string($match1));
Ideally the value of $match1 will be inserted into the segment of the SQL WHERE clause shown above - twice, each wrapped by '%' characters for a wildcard search.
If $match1 = "test", the resulting string value of $search_clause would be:
(msgBody LIKE '%test' OR msgSubject LIKE '%test%' )
What is the obvious mistake I'm making??
The $s is probably getting interpreted as a variable (see variable expansion). Try using single quotes instead:
$search_clause = sprintf(' (msgBody LIKE "%%%1$s%%" OR msgSubject LIKE "%%%1$s%%" ) ', mysql_real_escape_string($match1));
Just escape the $ as \$.
$search_clause = sprintf(" (msgBody LIKE %%%1\$s%% OR msgSubject LIKE '%%%1\$s%%' ) ", mysql_real_escape_string($match1));
^ ^

Categories