Manually escaping in PHP/MySQL - php

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

Related

SQL Server Escape String

I'm using this question as a reference. My issue is that it's encoding my string to hex, but not decoding it once it's written to the database.
HTML textarea
<textarea class="form-control" rows="5" name="nomInfo[]" id="appNom" placeholder="Additional Information"></textarea>
Getting POST value and inserting into the DB
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
$nomInfo = $_POST['nomInfo'][0];
$nomInfoDecode = mssql_escape($nomInfo);
$query = "INSERT INTO dbo.emp_recog (nomInfo) VALUES (";
$query .= "'" . $nomInfoDecode . "');";
So for example, if I types in ggfdgdfg/fdg.fdgdf.gdf "fdskfdskfds;fsd ' sdfds' fds/f% into the textarea and submit the form, this is written to the database 0x67676664676466672f6664672e66646764662e676466205c226664736b6664736b6664733b667364205c272073646664735c27206664732f6625
Scrap all the hex stuff, there is no need. Really the only thing to worry about escaping is a quote '. MySQL uses a slash \ as an escape character. MS SQL uses a quote ' to escape a quote ', so you just double-up the quotes:
return str_replace("'", "''", $data );
However, you really should be using PHP Data Objects that supports MS SQL, then there is PDO::quote.
I'm pretty sure the example is not quoting the value to be inserted:
mssql_query('
INSERT INTO sometable (somecolumn)
VALUES (' . mssql_escape($somevalue) . ')
');
which translated to your query using double quotes would be:
$query = "INSERT INTO dbo.emp_recog (nomInfo) VALUES (";
$query .= $nomInfoDecode . ");";
Can you give that a shot?

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.

Inserting to table where table name is a variable

I want to insert into a table where the table name is a variable. I can insert to the table just fine but when I try and make it a variable I get problems. I probably just don't know the syntax very well.
Below is without the variable
$query = $pdo->prepare('INSERT INTO test (item) VALUES (?)');
Below is what I need
$type = 'test';
$query = $pdo->prepare('INSERT INTO' + $type + '(item) VALUES (?)');
I also tried doing an escape_string
$type = 'send';
$type = mysql_real_escape_string($type);
I'm pretty sure my syntax is just off.
Try this:
$type = 'test';
$query = $pdo->prepare("INSERT INTO `{$type}` (item) VALUES (?)");
Also note that PHP uses dot . not plus + as string concatenation operator. But using double quoted string for the query you can use the table variable within the string and the variable gets interpolated.
You're missing spaces on either side.
'INSERT INTO ' . $type . ' (item) VALUES (?)'
would work because the $type would be separated by spaces on either side.
Note the space after INTO and the space before (item).

PHP: different quotes?

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.

Categories