get_where with md5() - php

I want to perform this simple query using Codeigniter:
$user = $this->db->get_where($type,array("id"=>$id));
$type is the name of the table and
$id is a md5() value so I want to do something like $this->db->get_where($type,array(md5("id")=>$id)); that of course is not possible to do.
the answer could be $this->db->query('select * from $type where MD5(id) = $id'); but I would prefer a more compact way like get_where() to perform query.
any suggestions?

$this->db->where('MD5(id)', $id, FALSE);
The 3rd argument when set to FALSE will stop CI from protecting your field and table names with backticks so instead of turning the code into:
WHERE `MD5(id)` = 'THE ID'
it will be:
WHERE MD5(id) = 'THE ID'

$this->db->get_where($type,array("md5(id)"=>$id)); works perfectly. I get the record I want.

To answer the original question which I came across recently and found this as the top result in Google.
$user = $this->db->get_where( $type, array( 'md5( id ) =' => $id ) );
You can also substitute = for other operators such as LIKE and NOT LIKE.

Related

How to search for 2 values in the same field with codeigniter?

I have a database field containing keyword ids ["1","2","3","4","5","6"] and I want to search for several of these ids in the same field.
Here is the idea of what I would like to achieve:
$tags[] = "\"1\"";
$tags[] = "\"2\"";
$query = $this->db->like(array('ids_keywords' => $tags[0], 'ids_keywords' => $tags[1]));
The problem here is that codeigniter only executes the last request instead of both because the search field is same.
What would be the best solution to do this?
try the following
$arrTags = [1,2];
$this->db->group_start()
foreach($arrTags AS $strTag)
{
$this->db->like(ids_keywords, '"'.$strTag.'"');
}
$this->db->group_end();
You can write your own clauses:
$where = "ids_keywords='1' AND ids_keywords='2' OR ids_keywords='3'";
$this->db->where($where);
For safe query use question mark(?)
$sql = "SELECT * FROM some_table WHERE ids_keywords = ? AND ids_keywords = ? AND ids_keywords = ?";
$this->db->query($sql, array(1, 2, 3));
In the above example, the question mark(?) will be replaced by the array in the second parameter of query() function. The main advantage of building query this way is that the values are automatically escaped which produce safe queries. CodeIgniter engine does it for you automatically.

PHP CodeIgniter Framework - Does Query Builder count as a prepare() and bind_param() and how to store form post data into Query Builder array?

I'm not finding much documentation-wise beyond some sources saying Query Builder statements are prepared, and others saying they are but not bound, then some saying they are bound etc. A solid answer would be much appreciated.
Furthermore, if I wanted to have my form data passed through into an array that I'm storing in my database, how should my following code be modified?
$user_first = $this->input->post('user_first');
$data['user_first'] = $user_first;
//this above code works fine if I want to store each part of the form
//in the array individually
$data = array(
'user_first' => 'My title'
//How can I get 'user_first' to => $user_first?
);
$this->pdo->insert('users', $data);
Thank you.
A few ways
//adding name by name to an array
$data = array('user_first' => $this->input->post('user_first'));
adding the entire post array
//as u have the same "name" in the form than the array u are sending to the db insert method
$data = $this->input->post();
//in short $this->input->post() is $_POST array, but cleaned
//or getting the values from $_POST
$data = array('user_first' => $_POST['user_first']);
Hope my answer helps u.
The answer depends to a large extent on what "prepared" means. "Binding" can be accomplished in a way very much like PDO. However, there are no methods that correspond to PDOStatement::bindColumn, PDOStatement::bindParam, or PDOStatement::bindValue.
The most direct equivalent to PDO::prepare() with "binding" would be as follows
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
The ? placeholders are replaced with the values in the array in the order they appear in the array. The input values will be escaped. The query() method does not support the PDO sytax of :name as a placeholder. (CI documentation on Query Binding.)
In general the various Query Builder methods combine to achieve the same overall effect as PDO::prepare() and PDOStatement::execute().
The functionality of PDOStatement methods to retrieve queried data (e.g. execute(), fetch(), etc.) are accomplished by calls to CI database methods for "Generating Query Results".
Assuming the three input from my example above have been posted by a here's how I would accomplish inserting them in a table
$data['id'] = $this->input->post('id');
$data['status'] = $this->input->post('status');
$data['author'] = $this->input->post('author');
$this->db-insert('some_table', $data);
If the element names are an exact match for the table column names and we know only those inputs will be posted the above could be simplified to
$this->db-insert('some_table', $this->input->post());

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

update query with functions in typo3

I'm trying to use the typo3 update function with the mysql CONCAT function. Can you tell me how to manage that? What I tried:
$updateArray = array("field" => 'CONCAT( field'.','.$toAppend.')');
$GLOBALS['TYPO3_DB']->exec_UPDATEquery ('table','id = '.'"'.$some_id.'"',$updateArray);
That does not work, because that query is executed:
UPDATE table
SET
pagesEdited='CONCAT( field,'value')'
WHERE
id = "id"
As you see, the concat function is escaped.
The reference documentation isn't very clear about it, however, just appending TRUE to your parameters of the update function should disable quoting:
$GLOBALS['TYPO3_DB']->exec_UPDATEquery ('table','id = '.'"'.$some_id.'"',$updateArray, TRUE);
That also means that you will have to do your own input sanitization before lauching the query, if you haven't already:
$toAppend = $GLOBALS['TYPO3_DB']->fullQuoteString($toAppend, "");
Have a look at the noQuote parameter of the fullQuoteArray() method of TYPO3\CMS\Core\Database\DatabaseConnection that is used by exec_UPDATEquery():
#param boolean|array $noQuote List/array of keys NOT to quote (eg. SQL functions) - ONLY for associative arrays
And when you take a kloser look ath this method, you will see that a simple true does not do the trick as expected. Simply use a list of fields (comma separated list) or an array to let TYPO3 know which fields should not be escaped.
In your case it would look like this:
$updateArray = array(
'field' => 'CONCAT(field,' . $GLOBALS['TYPO3_DB']->fullQuoteString($toAppend, 'table') . ')',
);
$where = 'id = ' . $GLOBALS['TYPO3_DB']->fullQuoteString($some_id, 'table');
$GLOBALS['TYPO3_DB']->exec_UPDATEquery ('table', $where, $updateArray, 'field');

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);

Categories