Failed to check the values has addslashes values in mysql - php

I have stored the datas in db with the addslashes when i submit the form.
Im stored values using the function like below
addslashes(trim($data[1]));
I want to check existing record in that table but its not working when it has value like
Regional Sales Director - Americas\'
Its checking existing values in table without those shlashes
\'
My query is
$query = $this->db->query("select * from tbl_contacts where contact_name='".$name."' and contact_company='".$company."' and contact_designation='".$designation."'");
$result1 = $query->result();

I'm not sure i should answer to this, but i feel i should because what you are doing is wrong in so many ways...
You should never ever do things like that if you want to insert data - especially if you use a framework which can do the job for you...
First of all you've to understand how Codeigniter inserts Data
Use the query builder
an example for inserting data would be
$arrData = [
'contact_name' => $this->input->post('contact_name'),
'contact_company' => $this->input->post('contact_company')
];
$this->db->insert('tbl_contacts', $arrData);
please read carefully the section in the CI Documentation here
and your select query is a disaster because you don't protect anything - you are widely open to any sort of attacks as Alex already said in the comments
Instead you should try the following:
$query = $this->db
->select('*')
->from('tbl_contacts')
->where('contact_name', $name)
->where('conatct_company', $company)
->where('contact_designation', $designation)
->get();
$result1 = $query->result();
Furthermore, please study the documentation, below are some links which are mandatory
Form Validation
Security Class
Input Class
Query Builder Class

If you've accidentally escaped your data with addslashes on top of existing database escaping: you may be able to methodically remove those back slashes with an update and replace to fix your data.
UPDATE tableName
SET columnName = replace(columnName, '\\', '');
But do be very careful, back up all your data first and test on a sample.
Then in the future, do not use addslashes on top of your database library's escape mechanism for updates or inserts.

Related

Pass sanitized input as column name in where clause

I have a function that accepts a $filter argument and then pulls data from an SQL table based on the filters in the argument. At first I tried overloading the function so that one function took a single $filter variable and another took an array for multiple filters. But then, I started wondering how I could sanitize the filter tag.
That may have been confusing so here are some examples. For example, a user types in the search box to display all users with the name John. So, $filter_tag would be set to say 'name' and $filter would be set to say 'John'. My PDO query would look something like this:
$query = "SELECT `name` FROM `users` WHERE ";
$query .= $filter_tag." = ?";
The issue is that $filter_tag is not sanitized. If I do sanitize it and the variable is escaped, then the query will not work. Maybe I am making this more complicated than it needs to be and there is some simple solution.
Please comment if you do not understand something that I am asking.
You could create a whitelist of valid tags:
if (in_array($filter_tag, ['name', ...], true)) {
$query .= $filter_tag . = '?';
}
Alternately you could remove all invalid characters, but I prefer the whitelist approach, because there are only that many valid column names :)
Lastly, instead of the above code you could also turn the condition around and raise an error if the given tag doesn't appear in the whitelist. In some cases this may be the better approach, because otherwise you may get an error later on because the number of arguments passed to ->execute() should match the number of placeholders in the query.

Codeigniter 2 $this->db->join used with $this->db->update

I just realized that you cannot use:
$this->db->join()
with
$this->db->update()
It seems the "join" is executed by codeigniter alright, but is not used in the query, seen after an update on the base table obtained with: $this->db->last_query();
I saw that there was no join. Then I tried an update on the joined table thinking the join would only been used if needed, but I did not work and told me the error 1054 "Unknown column XXX in where clause".
Is there a way to force codeigniter? The way I built my software, I REALLY don't want to build all the different parts of the queries myself (join, where) and the call $this->db->query().
NOTE: I saw these links:
Codeigniter active record update statement with a join
Is it possible to UPDATE a JOINed table using Codeigniter's Active Record?
codeigniter - database : how to update multiple tables with a single update query
but if someone knows a cleaner way it would be nice, because these solutions are not working with my case, since I was using the same joins in a "preProcessing()" method that uses the joins for a preview of the changes, then the same "preProcessing()" method is used for the replacement
Ok well I managed to find a "clean" solution, using codeigniter's join, set, etc. So what's cool is that you will have all CI's benefits of using $this->db->join(), $this->db->join(), etc. like escaping and adding quotes.
So first do all your CI stuff:
$this->db->join(..) // Set all your JOINs
$this->db->set(..) // Set your SET data
$this->db->where(..) // Set all your WHEREs
Then you can build the query using Active Record's ready, cleaned and escaped query elements:
// JOIN
$sql = "UPDATE $this->baseTable ";
$sql .= implode(' ', $this->db->ar_join);
// SET
$sql .= ' SET';
$setArray = array();
foreach ($this->db->ar_set as $column=>$newValue)
array_push($setArray, " $column = $newValue");
$sql .= implode(',', $setArray);
// WHERE
$sql .= ' WHERE '.implode(' ', $this->db->ar_where);
$this->db->query($sql);
If someone has a better solution, I will gladly accept it and use it instead

Zend framework queries and input validation

i'm new to zend framework (1.12), in my model, in my zend-db-table i want to validate the input (to avoid sql injection) and i want to do this query:
`SELECT id FROM friendships WHERE (user1= $user1 AND user2= $user2 ) OR (user1= $user2 AND user2= $user1 );`
in the example i have seen they use something like $db->quoteInto('string'); but in the model what i have to do? i can't write $this->quoteInto('string')...
second question is how can i put multiple values in quoteInto function? how do you validate input in your models? (not forms)
and last question, which steps do you follow to create an apllication usign zend framework? i mean, first you plan your project, second you write model, then you write controllers and finally views ( suppose you are alone to work on it ).
ps:I ask sorry for my english, but i hope you'll understand, thanks a lot and happy new year!!
Thanks a lot for the answer and sorry for delay...
i solved this way
$db= Zend_Registry::get('db');
$select=$db->select()
->from($this->_name)
->where("utente1= ".$db->quote($user1, 'INTEGER')." AND utente2= ".$db->quote($user2, 'INTEGER'))
->orWhere("utente1= ".$db->quote($user2, 'INTEGER')." AND utente2= ".$db->quote($user1, 'INTEGER'));
$stmt=$select->query();
$result=$stmt->fetchAll();`
i saved the db in my registry and i get it whenever i want...is there any security or other kind of problem doing this way?
about the planning, i was asking if there's a fixed procedure to work with zend, you're answer gave me a lot of relief... :)
anyway i started creating the database and now i'm working on models, when i'll finish i'll make views and controllers together.
i have a question about joins, can i select columns from both tables?, is right something like this:
$select = $db->select()
->from(array('p' => 'products'),
array('p.product_id', 'p.product_name', 'l.description'))
->join(array('l' => 'line_items'),
'p.product_id = l.product_id');
how can i do that?
Zend_Db_Table will provide the quotes most of the time, even when you don't explicitly use select() Zend_Db usually will:
//query is broken into multiple line for more clarity and is just an example
$select = $this->getAdapter()->select();
$select->from('friendships');
$select->where('user1 = ?', $user1);
$select->where('user2 = ?', $user2);//successive where() will tie together with AND
$select->orWhere('user1 = ?', $user2);
as long as your queries use the select() object they will be quoted.
When you need to do an insert or an update where the select object is not available use quoteInto():
//in your DbTable models
$where = $this->getAdapter()->quoteInto('user1 = ?', $user1);
$result = $this->getAdapter()->update($data, $where);
second question is how can i put multiple values in quoteInto
function?
the api is:
/* #param string $text The text with a placeholder.
* #param mixed $value The value to quote.
* #param string $type OPTIONAL SQL datatype
* #param integer $count OPTIONAL count of placeholders to replace
* #return string An SQL-safe quoted value placed into the original text.
*/
public function quoteInto($text, $value, $type = null, $count = null)
so multiple values are not really supported by quoteInto(), however there are other quote functions are available.
how do you validate input in your models? (not forms)
Use the same classes that you use when validating forms, use Zend_Validate and Zend_Filter. the easiest way is to use Zend_Filter_Input():
//multiple methods demonstrated
$filters = array('*'=>'StringTrim','zip'=> new Zend_Filter_Digits());
$validators = array('name'=>'Alnum');
$input = new Zend_Filter_Input($filters, $validators, $data);
if ($input->isValid()){//do some stuff}
and last question, which steps do you follow to create an apllication
usign zend framework? i mean, first you plan your project, second you
write model, then you write controllers and finally views ( suppose
you are alone to work on it ).
It's your application, do it how you want. Not meaning to be snide but the application will let you know what it needs. Typically you will get something to display and some data to manipulate. Then just go and build the plan.

SELECT Statement with array in WHERE clause

I am trying to track pageviews on my site whether a user is logged in or not and so I'm capturing the sessionId in my log. I only want to show tracking results for session ids that have at some point logged in and so my flow is as follows:
$pagestats = $wpdb->get_results("SELECT * FROM wp_user_stats WHERE uid=".$_GET['viewstats']);
$sessionArray = array();
foreach($pagestats as $checkSession)
{
if( !(in_array($checkSession->sessionId, $sessionArray)))
{
$sessionArray[] = $checkSession->sessionId;
}
}
Next, I am trying to gather all of the stats concerning any session Ids generated by this particular user ...
$sessions = join(',',$sessionArray);
$pagestats = $wpdb->get_results("SELECT * FROM wp_user_stats WHERE `sessionId` IN($sessions)") or die(mysql_error());
This is the part that throws the error. The error is:
Unknown column 'sjhntmqhltknks8pbhr750voe7' in 'where clause'
I don't understand why it's trying to find a column that matches the session Id instead of a result within that column.
The session IDs probably aren't getting quoted so the query looks like WHERE sessionID IN(abc, def, ...).
One way to fix that would be to change a line in the first loop:
$sessionArray[] = "'".$checkSession->sessionId."'";
Or you could create a second array with the quoted values.
The problem is that the session id is not numeric and needs to be wrapped in quotes. Something like the following would add proper quote to your $sessions string:
$sessions = "'" . implode("', '", $sessionArray) . "'";
You should also make sure you are escaping any user supplied input (e.g. $_GET['viewstats']) before using them to help avoid SQL injection attacks. It wouldn't hurt to escape $checkSession->sessionId as you are adding it to the $sessionArray array either.
If you are using a framework (it looks like you may be using WordPress) read the manual for the database component as it may provide functions to handle some of this for you.
I think you need to put quote around your session values
$sessions = "'".join("','",$sessionArray)."'";
Right now it's like WHERE IN (a,b,c) instead of WHERE IN ('a','b','c').
$pagestats = $wpdb->get_results("SELECT * FROM wp_user_stats WHERE `sessionId`=$sessions") or die(mysql_error());
This isn't an answer to the specific issue, but isn't the second SELECT statement unnecessary? If it is all stored in one table (unless there is a typo...) then SELECT * FROM wp_user_stats WHERE uid=$_GET['view_stats'] would retrieve all sessions for that user. Perhaps you need it done for multiple users? Even at that, you could simply do a GROUP BY clause.
Maybe I'm missing something though -- if so, sorry.

quickest way to update a Mysql Database

Just wondering what the best way to update an entire (large) database would be.
Bascially I have inherited a DB which had character issues, with some help I have sorted the character issues going forward (being written in) however the existing data needs cleaning up.
There was a good suggestion that I could use utf_decode to clean all this up - I have tried this on a wrong value in the page itself (when pulled in) and it works great.
As there seems to be a lot of tables, and alot of data, what's the best / quickest way to sweep all the data in the entire DB by using utf_decode ?
Thanks
Thanks for the comments, I can't seem to comment directly so dropping as message in here - I will have a look through and give them a go ! thanks.
Have you tried using the MySQL function CONVERT? Depending on your data, you may be able to update tables in a single statement, such as "UPDATE mytable SET myfield = CONVERT(myfield USING utf8)".
http://dev.mysql.com/doc/refman/5.0/en/charset-convert.html
Fetch all the data, convert it and insert it as:
INSERT INTO table VALUES (id, text)
(1, 'utf8'), (2, 'utf8'), (3, 'utf8')
etc.
Goes faster then to do a php loop with multi INSERT queries.
EDIT:
If you use a nice array, you could run a smooth system to do this:
$arr = array('users' => array('user_id', 'text', 'username', 'first_name')));
foreach(array_keys($arr) as $h) {
$query = mysql_query("SELECT * FROM {$h}");
while($row = mysql_fetch_object($query)) {
// Loop thingies, utf8_decode then and stuff
}
// Then implode them nicely and use above query
}
Tell me if you need more code example.

Categories