How do I escape a dot in insert query?
insert into './$x/.' () lues( );
How to escape the dot before $x and after $x, I tried the above but did not work.
Use forward slash, not back slash.
\
also, you need to escape things by placing the escape character BEFORE the thing it's escaping.
E.g.
"INSERT INTO `\$my_table` VALUES(NULL,$asdf,$jkl)"
Ok, but in your case, try this:
insert into `.$x.` () lues( );
Those are not ' but `
That is the backtick character. Same key as ~ on U.S. keyboards.
Concatenating a variable and a string:
$query = 'INSERT INTO `' . $my_table . '` VALUES(NULL,asdf,' . $jkl . ')";
But inside of double quotes "" you can just put the variable names into the string:
$query = 'INSERT INTO `$my_table` VALUES(NULL,asdf,$jkl )";
(Both of the above result in the exact same string being assigned to variable $query)
Take a look at the PHP page on strings
You can see sections on single quote, double quote, and others that will blow your mind (HEREDOC).
Related
I am passing array to postgresql in "WHERE" clause. but php is returning strings with double-quotes that postgrsql uses to define column. So postgresql is using the strings values as columns.
$allowed_A = \App\NewA::selectRaw("replace(unaccent(trim(name)), ' ', '') as newname")
->whereRaw('replace(unaccent(trim(name)), \' \', \'\') IN ("'.implode(",", $allowed_A).'")')->get();
Getting :
Undefined column: 7 ERROR: column "Purchase,Sale,...
How to fix it?
thanks
Your expression encloses the values in double quotes. Change it to this:
$A = \App\NewA::selectRaw("replace(unaccent(trim(name)), ' ', '') as newname")
->whereRaw("replace(unaccent(trim(name)), ' ', '') IN ('".implode("','", $allowed_A)."')")->get();
Pls. bear in mind that your approach is prone to sql injection.
I've got a script that imports data to a MySQL table and when inserting, VARCHAR and TEXT fields have double quotes on the beginning and end. I am using addslashes because some of the fields are supposed to have single quotes, double quotes, commas, and semi-colons. Here's my code:
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
$imports = array();
while (!feof($csvfile))
{
$csv_data[] = fgets($csvfile, 1024);
$data = explode(",", $csv_data[$i]);
$insert_csv = array();
$insert_csv['id'] = md5($EventID.$PerformerID);
$insert_csv['EventID'] = addslashes($data[0]);
$insert_csv['Event'] = addslashes($data[1]);
$insert_csv['PerformerID'] = addslashes($data[2]);
$insert_csv['Performer'] = addslashes($data[3]);
$insert_csv['Venue'] = addslashes($data[4]);
$insert_csv['VenueID'] = addslashes($data[5]);
$insert_csv['VenueStreetAddress'] = addslashes($data[6]);
$insert_csv['DateTime'] = addslashes($data[7]);
$insert_csv['PCatID'] = addslashes($data[8]);
$insert_csv['PCat'] = addslashes($data[9]);
$insert_csv['CCatID'] = addslashes($data[10]);
$insert_csv['CCat'] = addslashes($data[11]);
$insert_csv['GCatID'] = addslashes($data[12]);
$insert_csv['GCat'] = addslashes($data[13]);
$insert_csv['City'] = addslashes($data[14]);
$insert_csv['State'] = addslashes($data[15]);
$insert_csv['StateID'] = addslashes($data[16]);
$insert_csv['Country'] = addslashes($data[17]);
$insert_csv['CountryID'] = addslashes($data[18]);
$insert_csv['Zip'] = addslashes($data[19]);
$insert_csv['TicketsYN'] = addslashes($data[20]);
$insert_csv['IMAGEURL'] = addslashes($data[23]);
$query = "INSERT IGNORE INTO table_name(`id`, `EventID`, `Event`, `PerformerID`, `Performer`, `Venue`, `VenueID`, `VenueStreetAddress`, `DateTime`, `PCatID`, `PCat`, `CCatID`, `CCat`, `GCatID`, `GCat`, `City`, `State`, `StateID`, `Country`, `CountryID`, `Zip`, `TicketsYN`, `IMAGEURL`)
VALUES('{$insert_csv['id']}','{$insert_csv['EventID']}','{$insert_csv['Event']}','{$insert_csv['PerformerID']}','{$insert_csv['Performer']}','{$insert_csv['Venue']}','{$insert_csv['VenueID']}','{$insert_csv['VenueStreetAddress']}','{$insert_csv['DateTime']}','{$insert_csv['PCatID']}','{$insert_csv['PCat']}','{$insert_csv['CCatID']}','{$insert_csv['CCat']}','{$insert_csv['GCatID']}','{$insert_csv['GCat']}','{$insert_csv['City']}','{$insert_csv['State']}','{$insert_csv['StateID']}','{$insert_csv['Country']}','{$insert_csv['CountryID']}','{$insert_csv['Zip']}','{$insert_csv['TicketsYN']}','{$insert_csv['IMAGEURL']}')";
$n = mysql_query($query);
if(!mysql_query($query)){
die("error: ".mysql_error());
}
$i++;
What is causing the double quotes and how can I remove them when inserting the rows? I have also tried stripslashes on the VALUES part of the query but it causes an error due to fields that have single quotes, double quotes, or other delimiters.
Its possible your csv file contains fields that are delimited by double quotes. You can remove the double quotes from the fields by using the trim function. for example:
$insert_csv['EventID'] = trim(addslashes($data[0]), '"');
The above code will remove the double quote from the start and end of the $data[0] string.
TLDR: Instead of using addslashes() use a DB-specific escape function like mysqli_real_escape_string()
What addslashes() does is that it returns a string with backslashes before characters that need to be escaped.
I was going to write the whole explanation, but I think the php.net does a better job of explaining:
Returns a string with backslashes before characters that need to be
escaped. These characters are single quote ('), double quote ("),
backslash () and NUL (the NULL byte).
An example use of addslashes() is when you're entering data into
string that is evaluated by PHP. For example, O'Reilly is stored in
$str, you need to escape $str. (e.g. eval("echo
'".addslashes($str)."';"); )
To escape database parameters, DBMS specific escape function (e.g.
mysqli_real_escape_string() for MySQL or pg_escape_literal(),
pg_escape_string() for PostgreSQL) should be used for security
reasons. DBMSes have differect escape specification for identifiers
(e.g. Table name, field name) than parameters. Some DBMS such as
PostgreSQL provides identifier escape function,
pg_escape_identifier(), but not all DBMS provides identifier escape
API. If this is the case, refer to your database system manual for
proper escaping method.
If your DBMS doesn't have an escape function and the DBMS uses \ to
escape special chars, you might be able to use this function only when
this escape method is adequate for your database. Please note that use
of addslashes() for database parameter escaping can be cause of
security issues on most databases.
Looks like you have a csv file. I recommend using php's in-build fgetcsv() to read the file. This way, you will get an array for every row and then can use that array to insert into the database.
Also, you can directly import csv into mysql if you want it that way:
LOAD DATA INFILE 'D:/myfile.csv'
INTO TABLE my_table
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
i read string documentation on PHP and found out that Single quoted strings will display things almost completely "as it is." Variables and most escape sequences will not be interpreted except \' and \\
I wanted to display a hyperlink whose address should be http://localhost/kk/insert.php/?id="4"
i tried the following code
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=".$id."'>edit</a>";
But it's displaying http://localhost/kk/insert.php/?id=4 (there are no double quotes surrounding 4)
However, i accomplished the result by using
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
My question is that single quotes does interpret \" escape character. So why the first code is not displaying double quotes (that are placed inside single quotes). What am i missing?
You shouldn't have quotes around the integer. Your url should be
http://localhost/kk/insert.php/?id=4
which is accomplished using the following code:
$id = 4;
echo 'edit';
You're dealing with TWO languages there. PHP is doing the echo, and the " quotes are parsed/removed by PHP. Then there's the ' quotes, which are used in the HTML to delimit the href attribute.
With your escaped second version:
echo "<a href='http://localhost/kk/insert.php/?id=\"$display_result\"'>edit</a>";
^--php ^--html ^^--escaped for PHP
Normally that " before $display_result would TERMINATE the PHP string you've been echoing. But since it's been escaped (\"), the escape tells PHP to treat that quote as plaintext, and NOT as a quote. So the PHP string continues, and when this code actually executes and is output from your server, the browser will actually see:
<a href='http://localhost/kk/insert.php/?id="XXX"'>edit</a>
The interpretting difference between single quote and double quote you found is this:
$a = 4;
echo '$a' . "$a"; // $a4
// '$a' just prints `$a`
// "$a" prints `4`, it's interpretted
// alternatively "\$a" prints `$a`
As for the escaping. If your string delimiter is a single quote then you don't need to escape double quotes, and vice versa.
$a = "don't";
// vs
$a = 'don\'t';
$a = '"quote"';
// vs
$a = "\"quote\"";
To do it with your first example, just do :
$id = 4;
echo "<a href='http://localhost/kk/insert.php/?id=\"".$id."\"'>edit</a>";
I'm trying to get strings inside a quote.
I'm using regex but i have problems with escaped quotes.
For example, i have this:
$var = "SELECT * FROM TABLE WHERE USERNAME='Carasuman'";
preg_match_all('~([\'"])(.*?)\1~s', $var, $result);
$new = preg_replace('~([\'"])(.*?)\1~s',"<#################>",$var);
The code Works perfect. I got a replaced value in $new and quoted value in $result[1]
$new = "SELECT * FROM TABLE WHERE USERNAME=<#################>";
$result[1] = "Carasuman";
My problem is when i add a scaped quote inside quotes:
$var = "SELECT * FROM TABLE WHERE USERNAME='Carasuman\'s'";
I got this:
$new = "SELECT * FROM TABLE WHERE USERNAME=<#################>'s";
$result[1] = "Carasuman\" //must be "Carasuman\'s";
How I can avoid this error and get $new and $result[1] like first example?:
$new = "SELECT * FROM TABLE WHERE USERNAME=<#################>";
$result[1] = "Carasuman\'s";
Thanks!
for the match, you're never going to get Carasuman's without the \ as a single matched element since you can have match skip over chars within a single match. its either going to grab the Carasuman or Carasuman\'sjust use str_replace to get rid of the backslash
preg_match_all('~([\'"])(.*)\1~s', $var, $result);
$result[2] = str_replace('\\','',$result[2]);
for the replace, the ? in the (.*?) group makes it ungreedy, meaning it will stop at the first match. Remove the ? in (.*?) to make it greedy, meaning it will keep going until the last match
preg_replace('~([\'"])(.*)\1~s',"<#################>",$var);
Edit
Rather than doing the str_replace after the match on $result[2], it would probably be better to just do beforehand on the initial string like:
$var = str_replace("\\'","'",$var);
preg_match_all('~([\'"])(.*)\1~s', $var, $result);
$new = preg_replace('~([\'"])(.*)\1~s',"<#################>",$var);
You still need to make your wildcard match greedy like (.*?) to (.*) in order to have the apostrophe in the name included in the match/replace instead of being counted as the terminating single quote
Why don't you do this:
$var = "SELECT * FROM TABLE WHERE USERNAME='" . mysql_real_escape_string($input) . "'";
I don't think you necessarily need to do regex. Also, mysql_real_escape_string properly escapes your inputs so you can just have $input = 'Carasuman\'s'; or $input = "Carasuman's";
To match quoted strings, you could use the regex '\'.*?(?:\\\\.[^\\\\\']*)*\'' and four double quoted strings '".*?(?:\\\\.[^\\\\"]*)*"'
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.