Escape a literal so that it is wrapped with double quotes - php

We use doctrine 2 and want to write parameterised code like this:
attributes #> \'{' . $con->quote($attrId) . ':' . (int)$value . '}\'';
to have a query like this:
WHERE attributes #>'{"color":14}';
The "color" is the custom (user chosen) name of an attribute. So I feel that quote() is an appropriate function to shield it. But it wraps a parameter with single quotes, what makes the request syntax incorrect.
quoteIdentifier() function wraps with double quotes, BUT I'm not sure if it's right to use it in this context.
How to build a safe code to get the request I need?

Here is a way to do it with json_build_object and pg_exec_params:
<?php
$dbconn = pg_connect('');
$data = 'some"th\'ing';
pg_query_params($dbconn, 'SELECT json_build_object($1::text, $2::integer)', [$data, 14]);
?>
You need the explicit type casts so that PostgreSQL knows whether the argument is a string or a number.

You can include the double quotes in the string.
$attr = '{"' . $attrId . '":' . (int) $value . '}';
Don't depend on quoting to keep you safe, but instead execute the query with a method that binds the value to a prepared statement.
$statement = $con->executeQuery('SELECT * FROM your_table WHERE attributes #> ?', [$attr]);

Related

php variable is treated like string

I have this issue.
I need to receive, from comments column in mysql database, a string like this:
WHERE IDTable=$number
When i get this comment i have to put it like a Where clause in my query.
But if i write this code
$where=getComment($table,$field); //I get the string i wrote above
$number=5; //I initialize $number in my code
$sql="SELECT * FROM table $where";
print "SQL: $sql";
i get this:
SELECT * FROM table WHERE IDTable=$number
obviously i'd like to have in response:
SELECT * FROM table WHERE IDTable=5
How can I do that?
Thanks
I strongly suspect that the code you have a problem with is not the same code as above, as the above would not produce the result you stated. At the very least you are missing the definition of the function you're calling, to create said output.
However, what would produce such a result is by using single quotes around a string. Which prevents variable expansion, and treats them as regular strings instead.
Not only that, but your code is out of order as well. You cannot use a variable before you have declared it, as it simply does not exist yet.
The string returned by getComment() will not be parsed, so any PHP variables in it ($number) will be returned as the literal string.
I can think of two options -
1
Allow an extra parameter for getComment() so you can pass it $number
$number=5;
$where = getComment($table,$field,$number); // returns "WHERE IDTable=5"
$sql="SELECT * FROM table $where";
2
Do not return $number from getComment(), then you can add it when you build the query.
$where=getComment($table,$field); // returns "WHERE IDTable="
$number=5;
$sql="SELECT * FROM table $where $number";
Perhaps the String Value you got from MySQL: WHERE IDTable=$number may have been enclosed within Single Quotes. Consider the Example Below.
$number = 22;
$str = 'WHERE IDTable=$number';
var_dump($str); //<== YIELDS:: 'WHERE IDTable=$number' B'COS IT'S IN SINGLE QUOTES
$parts = explode("=", $str);
list($where, $var) = $parts;
$var = ltrim(trim($var), "\$");
$newStr = trim($where . "=" . $$var);
var_dump($$var); //<== YIELDS:: int 22
var_dump($newStr); //<== YIELDS:: 'WHERE IDTable=22' (length=16)
Assuming this is the case with your String; to get around that, You may simply want to extract the Variable from the String and then rebuild the String as the Snippet above demonstrates. Otherwise; if you have a possibility of enclosing the String in Double Quotes, this convoluted work-around would be utterly irrelevant.

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.

preventing calculations in variables during a select statement in MySQL

I'm trying to build a dynamic query based upon selections passed to a script. Example:
$qry = "SELECT * FROM machinekaart
INNER JOIN afleveradressen ON afleveradressen.raaid = mkrraaid
INNER JOIN kontaktpersonen ON kontaktpersonen.rkpraaid = mkrraaid
WHERE mkrrid != '' " ;
if($_SESSION['oud'])
$qry .= " AND mkrvo < " . $cur_jaar_maand;
Field mkrvo is a text field, and can contain yyyy-mm besides other values.
e.g. when the varable $cur_maand_jaar contains '2015-01' the selection will be everything lower than 2014
How can I stop this from happening and selecting everything lower than '2015-01' ??
I would suggest quoting that variable, so the values are taken literally:
if($_SESSION['oud'])
$qry .= " AND mkrvo < '" . $cur_jaar_maand . "'";
Better than that, please use PDO so you can use bindings, it's safer and best optimized.
Eg.
if($_SESSION['oud'])
$qry .= " AND mkrvo < ?";
// build your PDO Connection $myPdoConnection ...
$pdoStatement = $myPdoConnection->prepare($qry);
$pdoStatement->execute(array($cur_jaar_maand));
Within the SQL text, enclose the string literal in single quotes, so it's not evaluated as a numeric expression.
Evaluated in a numeric context: 2015-01 produces a value of 2014.
But '2015-01' is evaluated as a string literal.
(If the string literal is evaluated in a numeric context (e.g. '2015-01' + 0) the string will evaluate to a numeric value of 2015.)
The code you posted appears to be vulnerable to SQL Injection.
Consider what SQL text is generated when $cur_jaar_maand happens to evaluate to 0 OR 1=1 --.
A much better pattern is to make use of prepared statements with bind placeholders.

php using eval to obtain an objects attribute value

I am trying to set a function that will dynamically update an object attribute in the db w/o updating the whole object.
$sql = "UPDATE " . self::$table_name . " SET ";
$sql .= "$attribute = '" . eval("\$this->$attribute;") . "'";
$sql .= " WHERE ...";
I cant seem to get this eval("\$this->$attribute;") to produce the object attribute value. There is a value in the attribute and it is a public attribute.
Thanks
$attribute is a function var that will contain a string like 'address_id' so I want
UPDATE table_name SET address_id = '11' WHERE user_id='1'
This is a simple example of it
You don't need to do this using eval. PHP supports variable variables: http://php.net/manual/en/language.variables.variable.php
So this will do:
$this->$attributes
Note the second $ sign. This basicly means the value of $attributes is used as attribute name. If you want it to write a bit clearer you can do so using brackets:
$this->{$attributes}
This bracket is required if you wanted to do this using an array, or if you wanted to use multiple variables to build a variable name like this:
$this->{$var1}_{$array[0]}_{$var2}
This goes probably behind the scope of this question, but its good to know what variable variables are. But i don't recommend using them, because it makes the code unreadable and hard to understand.
There's no need to use eval():
$sql = "UPDATE " . self::$table_name . " SET ";
$sql .= "$attribute = '" . $this->attribute . "'";
$sql .= " WHERE ...";
If attribute is a variable, use:
$this->$attribute
Are you sure $this->attribute is sanitized correctly?

MySQL query php variable in variable?

I have a PHP function that makes a query to MySQL DB.
function regEvent($event, $l)
{
$sqlz_upd="UPDATE {$event} SET f1a='$_POST[F1A"'.$l.'"]'";
The question is what is the syntax to use variable $l in $_POST[F1A$l]?
$condition = $_POST["F1A" . $l];
$sqlz_upd="UPDATE {$event} SET f1a='".mysql_real_escape_string($condition)."'";
This is how to use your dynamic post and be safe for Sql Injection.
Here you go:
$var = mysql_real_escape_string($_POST["F1A".$l]);
$sqlz_upd="UPDATE {$event} SET f1a='$var' ";
if you are using a string as key in an associative array. It should be enclosed in single or double quotes(though PHP won't give any error).
i.e. $_POST['F1A'. $l] or $_POST["F1A$l"]
my suggestion will be...
$sqlz_upd="UPDATE {$event} SET f1a='" . $_POST["F1A$l"] . "'";

Categories