Zend 2 - DB - Escape value without quoting it - php

I'm looking for a clean way to escape value for SQL query without quoting it.
Let's say i have a value It's cool. Now I would like to simply get escaped string It\'s cool, just like when using for example mysqli_real_escape_string() function for mysqli driver.
The problem is that all Zend\Db\Adapter\Platform interface's quoting methods adds single quotes to the value which means I get 'It\s cool'.
Simplest way I found to do this is to trim quotes after usage of quoteValue() method.
$raw = "It's cool";
$quoted = $this->db->platform->quoteValue($raw);
$final = trim($quoted, "'");
But it's of course a dirty solution and I don't want it to be like this in every place I need escaped-only value.
Is there any clean way to do this simple thing in Zend2?

Maybe you can try something like this:
$sql = "UPDATE posts set comment = :value where id = :id";
$data = ['value' => "It's cool", 'id' => 123];
$stmt= $this->tableGateway->getAdapter()->createStatement($sql);
$stmt->prepare($sql);
$stmt->execute($data);

Related

PHP posting a variable in a variable using mysql

I need to use the number of the district to be the tail end of my variable. Example $publish_page_ADD THE DISTRICT NUMBER
I am grabbing the $district_num from my url which I've verified with echo
Here is what I've tried
$district_num = $_REQUEST['district_num']; // from url and works
$publish_page_.''.$district_num = $district_var['publish_page_'.$district_num.'']; //this does not work
$publish_page_.''.$district_num = addslashes($_POST['publish_page_'.$district_num.'']); //this does not work
$sql = "UPDATE districts SET
publish_page_$district_num = '$publish_page_$district_num' //this does not work and throws error "can not find publish_page_ in field list
WHERE district_num ='$district_num'"; //this works when the above code is removed
Follow up on corrected code... Thank You #cale_b and #Bill Karwin
$district_num = (int) $_REQUEST['district_num'];
$$publish_page = "publish_page_{$district_num}";
$$publish_page = $district_var[ "publish_page_{$district_num}"];
if (isset($_POST['submitok'])):
$$publish_page = addslashes($_POST[$publish_page]);
$sql = "UPDATE districts SET
publish_page_{$district_num} = '$publish_page'
WHERE district_num ='$district_num'";
If you want to learn about PHP's variable variables, it's in the manual (I linked to it). But you actually don't need it in your case.
Be careful about SQL injection. Your code is vulnerable to it.
Since you're using input to form a SQL column name, you can't use SQL query parameters to solve it. But you can cast the input to an integer, which will protect against SQL injection in this case.
$district_num = (int) $_REQUEST['district_num'];
$publish_page_col = "publish_page_{$district_num}";
The above is safe because the (int) casting makes sure the num variable is only numeric. It isn't possible for it to contain any characters like ' or \ that could cause an SQL injection vulnerability.
For the other dynamic values, use query parameters.
$publish_page_value = $_REQUEST["publish_page_4{$district_num}"];
$sql = "UPDATE districts SET
`$publish_page_col` = ?
WHERE district_num = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([ $publish_page_value, $district_num ]);
As #cale_b comments below, you should understand that in PHP, variables can be expanded inside double-quoted strings. See http://php.net/manual/en/language.types.string.php#language.types.string.parsing for details on that.

SQL bug or something else?

I have made a simple amateur component in Joomla...
In it there is a select>option drop-down list, which add parameters to the URL.
The problem was that it did not worked with 1.1 value and it works with a 1.5 value.
A friend of mine fixed the problem, but I want to know why it happened
Original Query:
$query = "SELECT * FROM `TABLE 2` WHERE Power='".$_GET["Power"]."' AND Poles='".$_GET["Poles"]."'";
The new working query:
$query = "SELECT * FROM `TABLE 2` WHERE Power=".floatval($_GET["Power"])." AND Poles='".$_GET["Poles"]."'";
If you're using Joomla, you should really be sticking to Joomla's coding standards and methods for everything, this includes database queries:
https://docs.joomla.org/Selecting_data_using_JDatabase
You should also be using JInput instead of $_POST or $_GET calls:
http://docs.joomla.org/Retrieving_request_data_using_JInput
Looking at your query, it should looking something like this:
$db = JFactory::getDbo();
$input = JFactory::getApplication()->input;
$power = $input->get('Power', '', 'RAW');
$polls = $input->get('Pols', '', 'RAW');
$query = $db->getQuery(true);
$query->select($db->qn(array('*')))
->from($db->qn('#__table'))
->where($db->qn('Power') . ' = ' . $db->q($power), 'AND')
->where($db->qn('Polls') . ' = ' . $db->q($polls));
$db->setQuery($query);
$results = $db->loadObjectList();
// Do what you want with the $results object
Using this means that column names and data values are escaped properly and you've not left with SQL vulnerabilities as #skidr0w mentioned.
Note: #__ is the database table prefix, assuming you've followed this approach. If not, simply replace #__table with the full name of your table
The table column Power is of type float or double. In your first query you try to insert a string value. The second query inserts the correct float by first casting the request value to float and removing the quotes around the value.
By the way, you sould never ever use unfiltered user-input (such as $_GET values) in a sql query.
Actually, after several days I found that the problem and the solution were simpler.
Just removing the '-sign solved the problem
Power='".$_GET["Power"]."'
with
Power=".$_GET["Power"]."
Regards

active record in codeigniter automatically adds quotes around where clause values

I've tried reading other posts on stackoverflow and also checked the active record documentation for ci, but i can't seem to find the answer to my question
I have the following logic in my model:
$query = $this->db->get_where('categories', array('parent_id' => $category_id));
the sql this generates as per the last_query() method is:
SELECT * FROM (categories) WHERE parent_id = '8'
I need to remove the quotes around the number 8. How would I do that?
I've tried using the select statement and passing false as the second parm. So for example:
$this->db->select('*', false);
$this->db->from('categories');
$this->db->where('parent_id=',$category_id);
But that didn't really change much. Any suggestions?
Thank you
By default, CodeIgniter tries to predict the data type in your comparison, and use the appropriate SQL syntax accordingly. If your query is using single quotes, it might indicate that $category_id is being treated as a string rather than an integer. What happens if you try:
$this->db->select('*');
$this->db->from('categories');
$this->db->where('parent_id', (int) $category_id);
Alternatively, you can construct your own WHERE statement manually:
$this->db->where('parent_id = ' . (int) $category_id);
For MIN and MAX query I used null and false keyword to remove the quotes.
$this->db->where("$value > min_column",null,false);
$this->db->where("$value < max_column",null,false);
The idea of the methods is to auto escape to protect against SQL injections, if for some reason you don't want to you can send a raw query like this :
$q = "select * from categories where parent_id = $category_id";
$this->db->query($q)->result();
Which i find much easier. However i think you can send an extra false paremeter to disable it, something like :
$query = $this->db->get_where('categories', array('parent_id' => $category_id),false);
FYI, if you want to send raw queries and escape them(for more complex queries) you can use :
$category_id = $this->db->escape($category_id);

Eval Purpose | SQL transormation?

I store my sql queries as strings and then use them later in PDO as shown below.
There is one line that I don't understand:
eval("\$query = \"$query\";");
From the docs..eval should run a string as PHP code. Why can't I just use $query directly? What does it mean to run a string of SQL?
This code works. I just don't know what eval() statement is for.
Note this is safe eval() as the input is not user defined.
"arc_id" => "SELECT id FROM credentials WHERE email=?",
"arc_id_from_hash" => "SELECT id FROM credentials WHERE pass=?",
"signin_pass" => "SELECT pass FROM credentials WHERE email=?",
"signin_validate" => "SELECT id, hash FROM credentials WHERE email=? AND pass=?"
);
public function __construct()
{
$this->db_one = parent::get();
}
public function _pdoQuery($fetchType, $queryType, $parameterArray=0) // needs review
{
$query=$this->sql_array[$queryType];
// what?
eval("\$query = \"$query\";");
// if not input parameters, no need to prep
if($parameterArray==0)
{
$pdoStatement = $this->db_one->query($query);
That code looks up the query by name, e.g. arch_id -> 'SELECT id ..', and then evaluates the query under a double-quote context in eval.
Presumable the queries could contain variables which would be interpolated. For instance, the original value might be 'SELECT id WHERE food = "$taste"' which would then then be evaluated as a double-quoted string literal in the eval and result in the interpolation of $taste so the result stored back in $query might then be 'SELECT id WHERE food = "yucky"'.
Given the data it appears to be "too clever" junk left over from a previous developer. Get rid of it. (If something similar is required in the future, although I would recommend strictly using placeholders, consider non-eval alternative mechanisms.)
eval("\$query = \"$query\";");
This is a variable replacer/templating engine.
It is replacing variables inside $query with their values.
I suggest not using eval for this, it'd probably be better to use preg_replace or str_replace.
For reference, here's a question I asked: PHP eval $a="$a"?

How to use PDO::quote without getting string surrounded by quotes?

I try to use PDO::quote to escape a string in a LIKE expression, so the user string must not be surrounded like in :
LIKE "%userStringToEscape%"
Is there a way to do that ?
$var = "%userStringToEscape%";
$var = $stmt->quote($var);
$sql = "SELECT * FROM table WHERE field LIKE $var";
same goes for the prepared statements
Use substr($db->quote($var), 1, -1)
Really though, don't. You'll end up with larger problems than the ones you started with.
The clean solution to do this is, of course, $db->quote('%'.$var.'%')
Just do:
$like = $pdo->quote("%{$userStringToEscape}%");
$sql = "SELECT * FROM field LIKE {$like}";
http://php.net/manual/en/pdo.quote.php

Categories