Codeigniter cannot delete rows from database table using join method - php

I want to delete from ‘table1’ those rows where (user_id = 5) but I should check if those posts’ (title = title1 in table2). I use Codeigniter and I get this error while trying to delete: ‘Deletes are not allowed unless they contain a "where" or "like" clause.’ Could you please help me to check what is wrong with my code below.
table1:
table2:
public function delete($title, $user_id){
$this->db->select('table1.*');
$this->db->from('table1','table2');
$this->db->where('table1.user_id', $user_id);
$this->db->where('table2.title', $title);
$this->db->join('table2','table1.post_id=table2.post_id');
$query = $this->db->get();
if ($query && $query->num_rows() > 0) {
$this->db->delete('table1.*');
$this->db->from('table1','table2');
$this->db->where('table1.user_id', $user_id);
$this->db->where('table2.title', $title);
$this->db->join('table2','table1.post_id=table2.post_id');
return true;
}
else {
return false;
}
}

Make use of subqueries.
example
#Create where clause
$this->db->select('id');
$this->db->from('table2');
$this->db->where('table2.title', $title);
$where_clause = $this->db->get_compiled_select();
#Create main query
$this->db->where('table1.user_id', $user_id);
$this->db->where("`id` NOT IN ($where_clause)", NULL, FALSE);
$this->db->delete('table1');
References
stolen from here: https://stackoverflow.com/a/16303021/1275832
about subqueries: http://www.mysqltutorial.org/mysql-subquery/
compiled select: https://github.com/NTICompass/CodeIgniter-Subqueries

After running first query you will get the set of user that you have to delete.
Run this set throw foreach loop for getting id of user and posts that you have to delete to an array.
$user_array = array();
$post_array = array();
foreach($query->result() as $query)
{
$user_array[$query->user_id] = $query->user_id;
$post_user[$query->post_id] = $query->post_id;
}
And then
this->db->where_in('user_id', $user_array)->delete('table1');
this->db->where_in('post_id', $post_array)->delete('table2');
I know that this is not the best decision. But i think that this is the most understandable.

You may use the following code to delete data from tables becasue codeigniter ignore join when you delete multiple data from multiple tables.
$sql = "DELETE t1 FROM table1 t1
JOIN table2 t2 ON t1.thing_id = t2.id
WHERE t2.otherthing_id = ?";
$this->db->query($sql, array($id));

JOINS are used to fetch data from database not used to delete data if you want to delete data from multiple table using single query then you need to use cascading in MySQl using that you can delete data also from other tables that are related to current table.

Related

how to pass variable value to sql query in codeigniter?

is it possible to pass the variable value in mysql query in codeigniter ?
I want to select records from database that have id same as my session id.
my code is :
$this->db->select('*'); // <-- There is never any reason to write this line!
$this->db->from('products');
$this->db->where('id_admin = (SELECT id_admin FROM users WHERE id='.$this->session->userdata('user_id').')', NULL, TRUE);
can we concatenate variable values in database queries?
This code not given any error, but not give any result also.
Use join in active records
$this->db->select('p.*');
$this->db->from('products as p');
$this->db->join('users','p.id_admin=users.id');
$this->db->where('users.id',$this->session->userdata('user_id'),false);
$query = $this->db->get();
An Example Reference of how to write the JOIN Query in CI as per the Documentation of the Active Records.
$article_id = $this->input->post('article_id');
$this->db->select('*');
$this->db->from('articles');
$this->db->join('news', 'news.id = articles.id');
$this->db->where('articles.id',$article_id);
$query = $this->db->get();
The above code will produce the query as follows for execution.
SELECT * FROM articles JOIN news ON news.id = articles.id WHERE articles.id='10'
Provided the passed id is 10
In order to view the Result of the executed query you must perform the below code.
print_r($query->result());
Try like this..use joining of two tables.
<?php
$this->db->select('products.*');
$this->db->from('products');
$this->db->join('users','products.id_admin=users.id_admin');
$this->db->where('users.id',$this->session->userdata('user_id'));
$query = $this->db->get();
print_r($query->result_array());//your array of records

More efficient way to grab MySQL row populated with single value

Right now I'm trying to set a variable from an SQL response without doing it more than necessary.
The situation is I have a SQL result from a SELECT + JOIN query with a user_id column that has only a single value. The other columns are different per row and I need to loop through them for that data. I was wondering if there was a way to extract the homogeneous value from the user_id column without setting it over and over again to a variable in my while loop.
Code:
#where I would like the $user_id to be set
while($responseArray = $response->fetch_assoc()){
$userId = $responseArray["user_id"]; #what I don't want to do
#other fetching stuff
}
SQL:
SELECT users.username, users.user_id, posts.post_id, posts.post_content, posts.number_comments, comments.comment_id, comments.comment_post_id
FROM users
JOIN posts
JOIN comments
WHERE delete_bit = 0 AND username = "john";
You cannot get away from fetching at least one result row. Even the fetchOne()-type functions do this. But if you only want a single row, why even bother using a loop in the first place?
$result = $db->query(...);
$row = $result->fetchRow();
$value = $row['somefield'];
would be far better than something silly like
$result = $db->query(...);
while($row = $result->fetchRow()) {
$value = $row['somefield'];
break;
}

Joining tables from two databases using codeigniter

In order to write query in codeigniter you need to write something like $this->db->query or $someDB->query. But what if I want to join tables from two different databases?
I know that I can do it through pure php, using mysqli_connect and writing something like:
SELECT * FROM db1.table1 JOIN db2.table2
But is there a way to do it using codeigniter?
Use query method from CodeIgniter and pass any complex sql query trough:
$query = $this->db->query("SELECT * FROM dbname1.table t1 JOIN db2.table t2 ON t2.column = t1.column");
foreach ($query->result() as $row)
{
print_r($row);
}
This simple join of student and teacher table with same column name , Hope you will get it .
$this->db->select("s.*,t.*");
$this->db->from("student as s");
$this->db->join("teacher as t","s.student_id = t.student_id","both");
$result = $this->db->get()->result_array();
return $result;
also you want single row try row_array(); instead of result_array();
You can try to use the function I am using in a project I am working on right now... Please see the code below...
function join_table()
{
$this->db->select(//column name, //column name, //column name);
$this->db->from(//table1 name);
$this->db->join(//table2 name, //table1 name.//column name = //table2 name.//column name');
$this->db->where(//condition);
return $this->db->get()->result();
}

How to get all records from two tables with three joins in CodeIgniter?

I have three tables (questions, answers, user) and I want to query all questions and answers posted by user.
Here is my code:
$query = $this->db->select('user.*,questions.*,answers.*')
->from('user')
->join('questions','questions.user_id = user.u_id','LEFT')
->join('answers','answers.user_id = user.u_id','LEFT')
->where('user.u_id',$profile[0]['u_id'])
->group_by('user.u_id')
->get();
echo $query->num_rows();
I have 1 posted question and 1 answer in my tables, but when I am trying this code it gives me only 1 row.
Try this with method..
write your query in single line like this
$query= "select * from user where" ; as well ( this is only query example you have to write your query)
then
if ($result = mysqli_query($connection, $query )) {
/* fetch associative array */
while ($res = mysqli_fetch_assoc($result)) {
print_r($res);
}
mysqli_free_result($result);
}
in this case $connection is a your database connection
Have you tried outer join, instead left join?
Maybe even a left outer join, solves your problem, just try it.
Oh, and instead of 'num_rows()' i suppose you just want to use 'row()' to
retrieve all table´s data.
$this->db->select('user.*,questions.*,answers.*');
$this->db->join('questions','questions.user_id = user.u_id','OUTER LEFT');
$this->db->join('answers','answers.user_id = user.u_id','OUTER LEFT');
$this->db->where('user.u_id',$profile[0]['u_id']);
$this->db->group_by('user.u_id')
$query = $this->db->get('user')->row();
echo $query;
I´ve changed a little your write, just copy and test it if you´d want

where in table A but not B in CodeIgniter

i am using codeigniters sql selection to select users where not in a set of id's.
$this->db->select('fbuid')->where_in('fbuid', $friends);
$query = $this->db->get('users');
im am trying to add another clause where it check for and not in friends table (id column). im trying to add use
$this->db-where_not_in
but i can't seem to get it to work
heres a pseudocode sql statement
SELECT fbuid FROM users WHERE IN () BUT NOT IN the friends TABLE ID COLUMN
Try this:
$query = $this->db->select('fbuid')
->from('users')
->where_in('fbuid', $friends)
->where_not_in('fbuid', $otherFriends);
EDIT:
You can either make a subquery before and store it in array OR do this in one step:
$query = $this->db->select('fbuid')
->from('users')
->where_in('fbuid', $friends)
->where('`fbuid` NOT IN (SELECT `uid` FROM `another_table`)', NULL, FALSE);
NULL, FALSE are important.

Categories