PHP: different quotes? - php

What is the difference between the quotes " and ' ? What about `? Is there an error in using different quotes ' and " below?
$result = pg_query_params($dbconn,
'INSERT INTO users
(username, email, passhash_md5)
VALUES ($1, $2, $3)',
array($username, $email, $passhash_md5
)
$result = pg_query_params( $dbconn,
"SELECT user_id
FROM users
WHERE email = $1",
array( $email )
)

Variable-substitution isn't done when using single quotes ('), meaning that the values in your first example would literally be $1 $2 etc if it was a regular string and not passed on to a function that replaces them.
If you don't need variable-substitiution, it's better to stick with single quotes for performance reasons.
`` invokes the shell-engine and invokes it as an actual command, and returning the result, just like in perl. Hence, it has a completely different meaning.
examples:
$email = 'user#example.org';
$sql1 = "SELECT user_id FROM users WHERE email = $email";
$sql2 = 'SELECT user_id FROM users WHERE email = $email';
$sql1 would be SELECT user_id FROM users WHERE email = user#example.org
$sql2 would be SELECT user_id FROM users WHERE email = $email

Basically, " lets you embed variables like so:
<?php
$beer = 'Heineken';
echo "$beer's taste is great"; // works; "'" is an invalid character for variable names
echo "He drank some $beers"; // won't work; 's' is a valid character for variable names but the variable is "$beer"
echo "He drank some ${beer}s"; // works
echo "He drank some {$beer}s"; // works
?>
(From the php manual)
Using ' means that no checking for variables is done.
<?php
echo '$beer';
?>
Would output $beer.

The difference between single and double quoted strings is well explained in the PHP manual about Strings.
In your example, since you are using substitution variables such as $1 that mean something specific to pg_query_params and that you do not want PHP to interpret as variable names, you should use single quotes for your SQL query strings.

Related

Why does this piece of code not work, when I pass value through input text?

I don't know why this piece of code did not work, when I pass value through input text?if i am violating the rules then what is it,s correct format.
<?php
$id1 = $_POST["id1"];
$name = $_POST["name"];
$update = $_POST["update"];
echo $id1; //working
echo $name; //working
echo $update; //working
mysqli_query($conn , 'update insert1 set '.$name.' = '.$update.'
where id-1 = '.$id1.'' ); //not working
// but if I manually use this as follows it works correctly
mysqli_query($conn , 'update insert1 set name = "new" where id-1 = '1'' );
?>
I'd wrap $update with single quotes (notice that I flipped the quotations) and changed id1 into $id1:
mysqli_query($conn , "update insert1 set ".$name." = '".$update."'
where id-1 = ".$id1 );
If id-1 is a string column type in the database then I'd wrap $id1 with single quotes. like this:
mysqli_query($conn , "update insert1 set ".$name." = '".$update."'
where id-1 = '".$id1."'" );
Notes:
I'd double check if id-1 is intended in the WHERE condition, because it checks if the value in that column is 2 rather than 1. WHERE id - 1 = 1 is equivalent to WHERE id = 2 but more confusing to the reader (thanks to FirstOne for pointing that out).
As mentioned in another answer, your code is vulnerable for SQL injection, I'd check this: https://stackoverflow.com/a/16282269/4283725
First of all, please indent your code properly.
Then learn (or at least try to understand) how strings concatenation works. In PHP you can use single or double quotes for strings.
What I repeat everytime to my colleague is to try (if possible) to wrap a string into the right type of quote regarding what the string can (possibly) contain.
If you have a chance to have a single quote in your string (or in one of the variables concatenated into), wrap it into doubles.
If you have a chance to have a double quote in your string (or in one of the variables concatenated into), wrap it into singles.
This can seems obvious but if you keep that in mind every time you manipulate strings, you'll be on the way for well concatenating you strings AND variables.
Also way you are passing a full raw query as a parameter is not very readable.
Put in in a separate variable and try like that :
<?php
$id1 = $_POST["id1"];
$name = $_POST["name"];
$update = $_POST["update"];
$query = '
UPDATE insert1
SET ' . $name . ' = "' . $update . '"
WHERE id-1 = ' . $id1 . '
';
mysqli_query($conn, $query);
?>
You will notice that $name is not surrounded with quotes as it's a field name and not a value.
Again $id1 is not surrounded with quotes as it's an integer value and not a string value.
But if for some reason the id-1 field or your insert1 table stores numbers AS strings so you'll want to surround it with double quotes.
It appears you are not declaring a variable in your SQL statement.
Adding the dollar sign($) to declare that.
$id1 = $_POST["id1"];
$name = $_POST["name"];
$update = $_POST["update"];
echo $id1; //working
echo $name; //working
echo $update; //working
mysqli_query($conn , 'update insert1 set '.$name.' = '.$update.'
where id-1 = '.$id1.'' ); //not working
//but if i manually use this as folwing it works correctly mysqli_query($conn , 'update insert1 set name = "new" where id-1 =
'1'' );
?>
Also, your code is open for SQL injection.

MySQL UPDATE and INSERT both returning error message about bad syntax, but it is correct syntax when trying it on phpMyAdmin

I have a PHP program that will either INSERT a new row, or UPDATE the existing one if it's already there. When running on a browser, it returns errors.
But, the actual call runs OK on phpMySQL - no error reported and row is updated.
"Errormessage: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"updated", `conditions` =" ",' at line 1.
Code to connect to mySQL and make the update or insert is very simple
require_once ('mysqli_connect.php');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error($dbcon);
exit ;
}
Then I make the actual body of the call, which produces variable $call containing this (example is for UPDATE):
UPDATE `deal` SET `deal_lotus_source` = "updated", `conditions` =" ", `termsnotes` = " ", `walkprovision` = " ", `sector` = "Application Software", `industry` = "Airconditioning", `tgt` = "Bcd", `acq` = "E", `dtstart` = "2015/03/08" , `dtclose` = "2015/03/23", `dtexdivtgt` = "2015/03/17", `dtexdivacq` = "2015/03/17", `dtexdivtgtexp` = "2015/03/17", `dtexdivacqexp` = "2015/03/17", `acq` = "E",`stat`= "Closed",`acqtype`= "Domestic",`dealtype`= "Acquisition of Private Company Cash-Stoc",`analyst`= "Fred Blogs",`tgttkr`= "ABC",`tgtx`= "C",`tgtprec`= "$",`tgtpret`= "1",`tgtshrout`= "2",`acqtkr`= "D",`acqx`= "F",`acqprec`= "$",`acqpret`= "3",`acqshrsout`= "4",`dlvalue`= "5",`eacls`= "Actual",`tgtlaw`= "",`acqlaw`= "",`tgtbank`= "",`acqbank`= "",`tgtshrsoutfd`= "6",`acqshrsoutfd`= "7",`tgtdebt`= "8",`acqdebt`= "8",`suppress`= "0",`pricingp`= "",`terminate`= " ",`divstattgt`= "",`divstatacq`= "",`divfreqtgt`= "Quarterly",`divfreqacq`= "Quarterly",`divcurrtgt`= "$",`divcurracq`= "$",`divamttgt`= "0.000",`divamtacq`= "0.000", `cos` = "", `mot` = "" WHERE deal_id =578
and the code to update (or insert) is
if (!mysqli_query($dbcon, $call)) {
printf("Errormessage: %s\n", mysqli_error($dbcon));
die;
}
Any ideas?
You have to use single quotes arround the values:
UPDATE `deal` SET `deal_lotus_source` = 'updated', `conditions` =' ', `termsnotes` = ' ', `walkprovision` = ' ', `sector` = 'Application Software', ...
Quotes in PHP can be confusing, because depending on which type of quote you use there are (different rules](http://www.trans4mind.com/personal_development/phpTutorial/quotes.htm). The most important things (in this case) to keep in mind are these 2:
* If you have a variable ($var) inside double-quotes ("$var") then it will get substituted (your string will now contain value) whereas if it is in single-quotes ('$var') then it will NOT get substituted (it remains in your string as $var)
* If you are need single-quotes as part of your string then use double-quotes around the string. ("I don't like contractions and I can't bear to use them.") If you need double-quotes as part of your string then use single quotes to surround the string. ('He said, "Hello, Dear!" and she slapped him.')
You are using double quotes (note the values you want to compare conditions and termsnotes and etc. to) but you are going to want to change to single-quotes inside the string so you can surround the whole thing with double-quotes. This also has the advantage of allowing you to use variables inside it.
$call = "UPDATE `deal`
SET `deal_lotus_source` = 'updated',
`conditions` =' ',
`termsnotes` = ' ',
`walkprovision` = ' ',
...
`mot` = ''
WHERE deal_id =578";
Note that the only double-quotes in that whole line of code are the ones at the very beginning and ending of the string. If you want to put a double-quote inside the string then you would have to put a backslash in front of it.
One very important step when you are constructing a query in a string (especially if you are getting errors with it) is to actually look at it. Use echo "call=<pre>$call</pre><br />\n"; and then look very carefully at all your quotes and etc. You can actually copy/paste the results of this echo into phpMyAdmin and see if the actual query works in your sql tab - this is a great test.
In summary, quotes in PHP are very consistent and very powerful, but they do have the potential to change your string during the process of assigning the string to a variable. It's very important to verify that the string after assignment is the string that you expect.

Manually escaping in PHP/MySQL

I try to understand manually escaping in PHP. I read this example:
if ($_POST)
{
$query = 'UPDATE
hersteller
SET
zulieferer = \''.mysql_real_escape_string($_POST['zulieferer']).'\',
telefon = \''.mysql_real_escape_string($_POST['telefon']).'\',
city = \''.mysql_real_escape_string($_POST['telefax']).'\'
WHERE
id = '.$_POST['id'];
$update = mysql_query ($query) or die (mysql_error());
}
The statement starts by an apostrophe. Unfortunately I couldn't find a discription.
1st part?
'UPDATE hersteller SET zulieferer = \'
2nd part?
'.mysql_real_escape_string($_POST['zulieferer']).'
3rd part?
', telefon = \'
4th part?
'.mysql_real_escape_string($_POST['telefon']).'
The first part is this:
'UPDATE
hersteller
SET
zulieferer = \''
note the extra '.
The escape character \ is used to escape the first ' so that it's inserted as a character into the string rather than interpreted as the end of the string.
It's similar to this:
$message = 'Let\'s get started';
$query = 'INSERT INTO table SET value = \'' . $value . '\'';
A \ character marks the following character as "plain-text", or text that has no meaning. This way, your output would look like zuliefer = 'thevalue'.
For this example, if you don't like having to escape all the characters, you can start the variable with a double quote.
$query = "UPDATE
hersteller
SET
zulieferer = '" . mysql_real_escape_string($_POST['zulieferer'])."',
telefon = '".mysql_real_escape_string($_POST['telefon'])."',
city = '".mysql_real_escape_string($_POST['telefax'])."'
WHERE
id = '".$_POST['id'] . "'";
$update = mysql_query ($query) or die (mysql_error());
-More reading on single quotes and double quotes in PHP strings
-More reading on escaping
-PHP manual on strings and meanings of symbols inside them
The statement starts by an apostrophe. Unfortunately I couldn't find a discription.
In PHP you can define strings with a pair of ' or a pair of ".
The main difference lays in the fact that "-strings are also evaluated to seek for $ variables.
For both string types you can obviously escape the ' or " character in order to make it appear in the string:
echo "He said \"Welcome\".";
// He said "Welcome".
In your case, for example, assuming the POST variable to be equal to x:
'zulieferer = \''.mysql_real_escape_string($_POST['zulieferer']).'\''
// zulieferer = 'x'
Since that string doesn't use " I'd suggest you to refactor it to be:
$a = mysql_real_escape_string($_POST['zulieferer']);
$b = mysql_real_escape_string($_POST['telefon']);
$c = mysql_real_escape_string($_POST['telefax']);
$d = (int) $_POST['id'];
$query = "UPDATE hersteller
SET zulieferer = '$a', telefon = '$b', city = '$c'
WHERE id = $d";
On a side note: you shouldn't use mysql_* functions. Use prepared statements instead.
The code is a little hard to read for two reasons:
it uses single quotes within the SQL statement and for the php string
it is one long string spanning multiple lines
This might be easier to read:
$query = 'UPDATE '.
' hersteller '.
'SET '.
' zulieferer = "'.mysql_real_escape_string($_POST['zulieferer']).'", '.
' telefon = "'.mysql_real_escape_string($_POST['telefon']).'", '.
' city = "'.mysql_real_escape_string($_POST['telefax']).'" '.
' WHERE '.
' id = '.$_POST['id'];
Edit: Regarding your comment:
$query = "DELETE FROM description WHERE id = '" . $this->getId() . "'";
This serves the same purpose as my rewrite above, only exchanging the use of single and double quotes. It uses double quotes as php string delimiters and single quotes in SQL. Both variants are fine, since both PHP and MySQL allow both kinds of quotes. Your $query variable will actually contain DELETE FROM description WHERE id = '1234'. Please note, however, both versions are not syntactically identical. PHP handles double quotes a bit differently from single quotes. In double quotes, PHP will replace variable names with the contents of that variable, in single quotes it won't.
$query = "DELETE FROM description WHERE id='$id'"; <-- PHP will insert the variable $id
$query = 'DELETE FROM description WHERE id="$id"'; <-- PHP will not touch the string

Parse value to a mysql Query

I have this quick question, i have got the username variable from a form and i need to insert it in a query, can you please tell me where i'm going wrong, it says: Unknown column '$username' in 'field list'
Here is the code:
echo $HTTP_POST_VARS['username'];
echo $username;
$query = sprintf( 'SELECT $username FROM hostess' );
In the code supplied you never set $username.
You're wide open for Sql injection.
You're using sprintf without any reason - it formats a string but you're not supplying any formatting, my example below does
You're trying to 'SELECT $username FROM hostess' but that's not a valid Sql statement at all.
You'd be wanting something more like:
$query = sprintf( "SELECT * FROM hostess WHERE username='%s'", $username);
AFTER making sure you clean $username.
Uhmm about everything seems wrong..
First of all, you never defined the variable $username.
What you are doing would only be valid in a version of PHP that still supports suberglobals.
Second, why are you using sprintf for a query?
By the way, HTTP_POST_VARS is deprecated. Use POST
Correct code would be something like this;
$username = $_POST['username'];
echo $username;
$query = mysql_query("SELECT ".$username." FROM hostess");
in PHP, using the single quote for strings will not parse the string for variables. Use either concatenation or double quotes:
$query = sprintf( 'SELECT ' . $username . ' FROM hostess' );
$query = sprintf( "SELECT $username FROM hostess");
Of course, this is to say nothing about the terrible risks using a POST var this way implies.
$query = sprintf( 'SELECT %s FROM hostess', $username);
-or, if that's a string value, I suspect you may want to include that in single quotes in the query text -
$query = sprintf( "SELECT '%s' FROM hostess", $username);
NOTE: The generated SQL statement looks a bit odd, in that its going to return the same literal value for every row in the hostess table. If there's a hundred rows in the hostess table, you are going to return 100 rows with the same literal value. This may be what you want, but it strikes me as VERY odd.
NOTE: The sprintf function looks for %s, %d, etc. placeholders in the first argument, and replaces them with values from the remaining arguments.)
NOTE: If $username contains a value coming in from a form, and has not been validated, to thwart SQL injection attacks, I would use the (admittedly old school) mysql_real_escape_string function. (Others will offer suggestions for better, more modern techniques to accomplish the same result.)
$query = sprintf("SELECT '%s' FROM hostess",mysql_real_escape_string($username));

PHP script with MySQL statement with single quote

I'm learning PHP,MySQL and came across this function today
function get_director($director_id) {
global $db;
$query = 'SELECT
people_fullname
FROM
people
WHERE
people_id = ' . $director_id;
$result = mysql_query($query, $db) or die(mysql_error($db));
$row = mysql_fetch_assoc($result);
extract($row);
return $people_fullname;
}
I understand what functions are and I've created a few while learning PHP.But this one is a bit more complicated.I can't understand the
WHERE people_id = ' . $director_id
I guess the single quote ends the MySQL statement? And then it is concatenated with the argument?
Yes you are right, the single quotes end the sql string and concatenate with the supplied argument. Same case if you want to print the value out.
echo 'This is the director ID :'.$director_id;
I wouldn't call this operator an "SQL statement". And wouldn't say it is "closed" either.
For PHP it's just a string with no particular meaning.
And the quote ends this string literal, not SQL statement.
Strictly speaking here is just a concatenation, a string literal with a variable.
Having a whole complete SQL statement as a result.
The .(dot) is used for concatenation in php.
If you pass 32 to $director_id then the final query will be
select people_name from people where people_id = 32
If you pass 43 to $director_id then the final query will be
select people_name from people where people_id = 43
Means the .(dot) is used for appending the value of $director_id to the string in single quotes.
The final query will be passed to mysql. Using .(dot) is just a method in php to generate the final query that we want to execute in mysql.
I guess the single quote ends the MySQL statement?And then it is concatenated with the argument? Please help me out.
That is correct.
http://php.net/manual/en/language.operators.string.php
<?php
$a = "Hello ";
$b = $a . "World!"; // now $b contains "Hello World!"
$a = "Hello ";
$a .= "World!"; // now $a contains "Hello World!"
?>
EDIT: The meaning of the WHERE clause is best explained by the psuedo explanation of what the entire statement does.
SELECT everyone's full name WHERE their people_id is EQUAL TO some value passed into the function.
However, you are way over your head if you are evaluating these things and don't understand the basic SQL. I recommend you read the entire Tiztag PHP/MySQL tutorial.
http://www.tizag.com/mysqlTutorial/

Categories