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
Related
$this->fifo_db->select('u.name,d.title');
$this->fifo_db->from('tbl_user u');
$this->db->join('designations d','d.id = u.designationid','left');
$this->db->where(array('u.designationid > ' => 1,'d.salary > ' => '20000'));
$query = $this->fifo_db->get();
return $query->result_array();
Trying to fetch data in CI format using join on two tables from different DBs, getting error on the same.
I think you need to prefix the table references with the name of the database.
This code doesn't use Query Builder or table aliases for a couple of reasons.
To prove the concept of multiple databases it's easier to write the
complete query string.
I'm not sure how well aliases will work along
with the db name prefixes, nor do I know how to alias when including the db name.
I check the return of db->query because it will be FALSE if the query causes an error. If $query is FALSE a call to $query->result_array() would cause an exception to be thrown.
You need the actual database names. I've made up the names dbU and dbD.
$sql = "SELECT dbU.tbl_user.name, dbD.designations.title FROM dbU.tbl_user
LEFT JOIN dbD.designations ON dbD.designations.id = dbU.tbl_user.designationid
WHERE dbU.tbl_user.designationid > 1 AND dbD.designations.salary > 20000";
$query = $this->db->query($sql);
if($query !== FALSE)
{
return $query->result_array();
}
return NULL;
I don't think it will matter which CI database object (fifo_db or db) you use. I'm pretty sure the databases need to be on the same network server.
If the above works you can add the aliases and then, if that works, refactor it to use Query Builder. Frankly, I don't see any reason for QB based on the query shown. But you may have more complicated needs you're not sharing.
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.
I'm trying to update a value of a column using the codeigniter query function like this:
$this->db->query("UPDATE table SET val = val + 1 WHERE name = 'xxxxx');
Is there any way to get the result of this update in the same query function? I have to do a select query in order to do it and it's dangerous because of the amount of users this application is managing.
If there is another query in between the update and the select, the result would not be correct.
Thanks!
Use transaction and for update. This is an example from zend, which is a similar kind of db accessing thing:
$db->beginTransaction();
$val = $db->select()->forUpdate()->from('table', 'val')->orderBy('val DESC')->limit(1)->query()->fetchColumn();
$db->update('table', 'val = '.($val+1), 'name = "xxx"');
$db->commit()
The for-update with the transaction prevents another query interfering.
Learn more about for update here: http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html
and about codeigniter transactions here: http://ellislab.com/codeigniter/user-guide/database/transactions.html (thanks to #Nanne for that)
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.
I need to grab data from two tables, but I know theres a better, more tidier way to do this. Is it some kind of JOIN i need?
I'll show you my code and you'll see what I mean:
if ($rs[firearm] != "") {
$sql_result2 = mysql_query("SELECT * FROM db_firearms WHERE name='$rs[firearm]'", $db);
$rs2 = mysql_fetch_array($sql_result2);
$sql_result3 = mysql_query("SELECT * FROM items_firearms WHERE player='$id'", $db);
$rs3 = mysql_fetch_array($sql_result3);
if ($rs3[$rs2[shortname]] < 1) {
mysql_query("UPDATE mobsters SET firearm = '' WHERE id ='$id'");
}
}
This question is clear, but your code example has alot of formatting issues and I cannot give you direct answer, based on your example code.
The reason, why your example is unclear, is because.. with what are you going to join the tables? From one table you are selecting by name='$rs[firearm]' and from another by player='$id'. You have to provide the hidden data, like $rs and also $id.
You should definitely read these about mysql join and mysql left join. But I will try to give you an example based on your code, with fixed syntax. (Keep in mind, that I'm no mysql join expert, I did not test this code and also I do not know the joining conditions.) And also, the system structure is unclear.
As I understood, this what your tables do, correct?
mobsters - Users table
items_firearms - Links from users table to items table
db_firearms - Items table
So basically, my example does this: It will have preloaded $rs value, from the users table. It will check, if there is a entry inside the links table and hook the result with them items table. However, if the links table or even the items table can return multiple entries, then this doesn't work and you need to loop your results in much more smarter way.
// I can only assume, that $id is the ID of the player
$id = 2;
// Since I dont know the $rs value, then Im going to make some up
$rs = array(
'id' => 33,
'firearm' => 'famas'
);
if ($rs['firearm']) {
$result = mysql_fetch_array(mysql_query("SELECT ifa.*, dbfa.* FROM `items_firearms` AS `ifa` LEFT JOIN `db_firearms` AS `dbfa` ON `ifa.shortname` = `dbfa.shortname` WHERE `ifa.player` = '$id'"));
if ($result['id']) {
mysql_query("UPDATE `mobsters` SET `firearm` = '' WHERE `id` = '$id'", $db);
}
}
It is pretty clear, that you are new to PHP and mysql.. So I think you should probably edit your question and talk about your higher goal. Briefly mention, what your application are you building..? What are you trying to do with the mysql queries..? Maybe provide the table structure of your mysql tables..? I'm sure, that you will get your questions votes back to normal and also we can help you much better.
NOTES
You have to quote these types of variables: $rs[firearm] -> $rs['firearm']
If you want to check if your $rs['firearm'] equals something, then there is a better way then $rs[firearm] != "". The most simple is if ($rs['firearm']) {echo 'foo';}, but will produce a notice message, when all errors reporting mode. You can use isset() and empty(), but keep in mind, that isset() checks whether the variable has been set.. Meaning, even if its false, then it has been set. empty() reacts to undefined and empty variable the same, without any messages.
Also, "" means NULL, so if you even need to use "", then use NULL instead...much neater way..
I strongly recommend to use mysql class. You can understand the basics behind that idea from this answer. This is gonna make things much more easier for you. Also, mysql class is a must-have when dealing with dynamic applications.
if ($rs3[$rs2[shortname]] < 1) { .. makes no sense.. Do you want to check if the value is empty? Then (simple): if (!$rs3[$rs2[shortname]]) { .. and a very strict standard: if (empty($rs3[$rs2[shortname]])) { ..
Also you have to quote your sql queries, see my examples above.
Is the last mysql query missing $db?