I want to know why the following query have . and "" in ".$_POST['date']." etc.
$query = "INSERT INTO eventcal ('eventDate','eventTitle','eventContent','user',
'user_id') VALUES('".$_POST['date']."','".addslashes($_POST['eventTitle'])."',
'".addslashes($_POST['eventContent'])."')";
If I change to the following, will it make any differences?
VALUES('$_POST['date']','addslashes($_POST['eventTitle'])',
'addslashes($_POST['eventContent'])')
Thanks in advance.
It is the PHP form of concatenation (The quotes mark the end of the strings). In JavaScript and many other languages it is the + character that concatenates.
echo "hello" . " " . "world!"; // Outputs 'hello world'
Yes, making that change would drastically change its meaning.
Finally, this is open to a severe SQL injection attack because date is not properly escaped.
Always sanitize your input and use parameterized queries where possible.
The "dot" operator is PHP's operator for string concatenation. I think that using the addslashes function is a better idea than what you have in the first example but you will still need to use string concatenation as PHP's string interpolation only supports variables.
Single quotes inhibit variable interpolation, and as well the single quotes used in the array index would terminate the string.
Also, use a library that supports query parametrization instead of adding the values in like this.
Yes, only variables are parsed in double quotes which means your functions won't be executed in the second code block.
Related
I am new to Laravel and I am having this question.
I tried out this line of code and it works fine: return redirect("/cards/{$note->id}");
But when ever I try to use the single quotes, it does not work: return redirect('/cards/{$note->id}');
How can I solve this problem ?
What you are doing first is called variable interpolation or string interpolation. You can read more about it here, on PHP docs and here, on Wiki.
It's a feature in PHP that allows you to pass a string and have variables/placeholders inside interpreted.
In your second example you are using single quotes, which does not provide this feature, so you will have to break it up and add the variable manually to the string:
return redirect('/cards/' . $note->id);
If you are interested in a more elaborate explanation and the performance behind it then you can read more on this answer here by Blizz
He concludes that:
Everyone who did the test concluded that using single quotes is marginally better performance wise. In the end single quotes result in just a concatenation while double quotes forces the interpreter to parse the complete string for variables.
However the added load in doing that is so small for the last versions of PHP that most of the time the conclusion is that it doesn't really matter.
You should use "/cards/{$note->id}" or '/cards/'.$note->id
The most important feature of double-quoted strings is the fact that variable names will be expanded.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
From PHP documentation
Use it like that:
return redirect('/cards/'. $note->id);
With either single or double quotes
I'm working to integrate a plug-in into a PHP web application, and one line of the code puzzles me:
$sql = "update inventory set qtyleft='$qtyleft',price='$price',sales=sales+'$sales',qtysold=qtysold+'$qtysold' where id='$id'";
mysql_query($sql);
where $qtyleft, $price, $sales, $qtysold and $id are all variables.
I'm not very familiar with PHP, but I always thought string concatenation in PHP is done by using the . operator and it seems to me that the code above is just a long string without actually putting those variables to the SQL query. Is that the case?
In PHP, double quote (") delimited strings will evaluate variables in them.
$foo = 42;
echo "The answer for everything is $foo"; // The answer for everything is 42
This specific example is very bad because you shouldn't include variables directly in an SQL query, and shouldn't use mysql_query in new code.
See more:
Why shouldn't I use mysql_* functions in PHP?
How can I prevent SQL injection in PHP?
See Variable Parsing section of the Strings manual page.
When a string is specified in double quotes or with heredoc, variables are parsed within it.
If you use single quotes for a string, the variables will not be interpolated. If you use double quotes, they will be.
The code you mentioned will work in PHP without any issues. Please refer PHP Manual for more details.
Other issue that you might need to look forward is the function mysql_query is depreciate. Please refer here. Which gives me a feeling that the plugin you are going to is use not maintained correctly. And one more problem is, its not a good practice to pass the variable directly in the SQL query do to possible security issues
Some call it "variable interpolation". It is explained on the Variable parsing section of the manual page about strings. It helps to read the entire page and also the user comments.
The basic idea is that for strings enclosed in quotes (") and on heredoc blocks, PHP searches for variables inside the string when it needs to use it and replaces them with their values at the moment of the execution. This means the same string can render to different values in different moments of the script's execution.
This is just syntactic sugar, it doesn't change the way the code behaves and any string that contains variables inside can be rewritten using the string concatenation operator (.). Usually this syntax produces shorter source code. Sometimes the code is easier to read this way, other times it is harder because the complex expressions (array access, f.e.) need to be enclosed in curly braces ({ and }) inside the string.
I have some question about saving html code in mysql database
every time when I put the charter " ' " in the database it changes to " / ".
Example:
somthing like that
<p>That's my name</p>
After saving it look like this:
<p>That\'s my name</p>
what can i do?
thank u all
Use parameterized queries to escape data going into the database
Use nothing else to escape data going into the database (otherwise you will double escape which can use this problem)
Do not use mysql_real_escape_string
Do not use addslashes
etc
Do not escape data coming out of the database (since that will cause this problem)
Make sure magic quotes are disabled (since having them turned on will escape data going into and out of the database and cause this problem).
You are using addslashes like escape functions in your code.
addslashes() — Quote string with slashes - http://php.net/manual/en/function.addslashes.php
stripslashes() — Un-quotes a quoted string - http://php.net/manual/en/function.stripslashes.php
Use stripslashes to remove '\' from HTML data. Actually (') is used define string in MySql, so it ecaspe it (by putting \ in-front) in order to avoid any unintentional use.
I'm building an application around a database(which was built by someone else, so changing it is not an option). I'm querying the database for values which was working fine until I came across a column in the database that has a $ in it.
The code I'm trying to get to work is...
$avgprice=mysql_result($result1,$i,"avg$cwt");
Try to escape $ sign or use ' instead of ":
$avgprice=mysql_result($result1,$i, "avg\$cwt");
// or imho better way to do it:
$avgprice=mysql_result($result1,$i, 'avg$cwt');
PHP strings:
When a string is specified in double quotes or with heredoc, variables are parsed within it.
and
Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
Use single quotes ' instead of double quotes " to prevent PHP from trying to replace the assumed variable.
$avgprice=mysql_result($result1,$i,'avg$cwt' );
PS: Maybe consider using PDO or mysqli instead of the plain mysql_X functions.
Use single quotes.
$avgprice=mysql_result($result1,$i,'avg$cwt');
Double quotes interpolate (expand) variables. Single quotes do not. Good practice in PHP is to only use double quotes if you want to interpolate variables in the string. Single quoted strings are processed faster because the interpreter doesn't have to look for variables.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between single quote and double quote string in php
Can you use " and ' interchangeably, 100%? Or is there a reason or use for each? What is the difference exactly?
Observe for yourself:
$name = 'John';
echo "Hello $name" . '<br>';
echo 'Hello $name';
Result:
Hello John // result from double quotes
Hello $name // result from single quotes
As can be seen variables inside double quotes are parsed while in single quotes they aren't.
So when you put variables inside double quotes, they can be parsed and their correct value is output whereas with single quotes, variables are not parsed and you get the same output of variable name itself as in Hello $name.
Since variables inside single quotes aren't parsed, using them is just a little good when it comes to performance.
If there is no question of variables inside quotes, you can use them inter-changeably though keeping above performance tip in mind.
For more information, you can look at the official documentation.
Just to add to the great answer of Sarfraz, there are certain situations where you would want to use one or the other.
Single quotes ('') are always parsed slightly (minutely) faster than double quotes so if you are an optimization freak, a good rule of thumb is to use single quotes instead of double quotes if you will not be parsing any variables.
However, if you have tons of variables and don't want to do something like:
echo 'My name is ' . $name . '!';
then you're better off with double quotes.
However when dealing with html output, you may consider the hassle of escaping your double quotes too tedious to deal with:
echo "<p id=\"myParagraph\">$name</p>";
So in this case the vote goes to single quotes.
Another thing is that when you build SQL queries with PHP, you may notice that you might prefer using double quotes to be able to parse variables and avoid escaping the single quotes:
"SELECT * FROM CoolGuys WHERE Name = '$name'";
In the end it's all a matter of preferrence. :)
Good luck!