how to using SQL INSERT INTO SELECT with codeigniter - php

How to use the SQL insert into select in CodeIgniter.
Model...
public function history($book_id)
{
$query = $this->db->query('INSERT orders (book_id, title)
SELECT book_id, book_title
FROM books
WHERE book_id = \'$book_id\'');
return true;
}

First of get all books from books table then INSERT order according to your $book_id
Example:
public function history($book_id)
{
$this->db->select('book_id, book_title');
$this->db->from('books');
$this->db->where('book_id', $book_id);
$query = $this->db->get();
if ( $query->num_rows() > 0 ) // if result found
{
$row = $query->result_array(); // get result in an array format
$data = array();
foreach($row as $values){
$data = array(
'book_id' => $values['book_id'],
'title' => $values['book_title']
);
$this->db->insert('orders', $data); // insert in order table
}
return true;
}
else{
return false;
}
}

Related

CodeIgniter 3 - joint data from another table

Original function:
function getRows($id = ""){
if(!empty($id)){
$query = $this->db->get_where('orders', array('id' => $id));
return $query->row_array();
}else{
$query = $this->db->get('orders');
return $query->result_array();
}
}
I need to JOIN data from table order_shipping and order_products where order_id = order_id
I do:
/*
* Fetch user data
*/
function getRows($id = ""){
if(!empty($id)){
$query = $this->db->get_where('orders', array('id' => $id));
return $query->row_array();
}else{
$this->db->select('*');
$this->db->from('orders');
$this->db->join('order_shipping', 'orders.id = order_shipping.id');
$this->db->join('order_products', 'order_shipping.id = order_products.id');
$query = $this->db->get('');
return $query->result_array();
}
}
This above code working correct. But currently JOIN only after else. I need do the same way before else:
* Fetch user data
*/
function getRows($id = ""){
if(!empty($id)){
$this->db->select('*');
$this->db->from('orders');
$this->db->join('order_shipping', 'orders.id = order_shipping.id');
$this->db->join('order_products', 'order_shipping.id = order_products.id');
$query = $this->db->get('', array('id' => $id));
return $query->row_array();
}else{
$this->db->select('*');
$this->db->from('orders');
$this->db->join('order_shipping', 'orders.id = order_shipping.id');
$this->db->join('order_products', 'order_shipping.id = order_products.id');
$query = $this->db->get('');
return $query->result_array();
}
}
But this code before else not working correct for me and currently display wrong data. When I try fetch all orders, then second function display correct all orders. But when I try fetch example only order ID 2, then is used first function and display wrong data, example when I fetch order ID2, then always display only order with ID 1.
This function is for REST API fetch orders.

join 2 table in one function

i want to join the data of 2 tables in 1 table and display the data of 2 tables. I already have function that load the one table. can someone modify this function code to get the 2 tables ? im just a beginner in php.
Model_users.php
public function getUserGroup($userId = null)
{
if($userId) {
$sql = "SELECT * FROM user_group WHERE user_id = ?";
$query = $this->db->query($sql, array($userId));
$result = $query->row_array();
$group_id = $result['group_id'];
$g_sql = "SELECT * FROM groups WHERE id = ?";
$g_query = $this->db->query($g_sql, array($group_id));
$q_result = $g_query->row_array();
return $q_result;
}
}
Controller User.php
public function index()
{
if(!in_array('viewUser', $this->permission)) {
redirect('dashboard', 'refresh');
}
$user_data = $this->model_users->getUserData();
$result = array();
foreach ($user_data as $k => $v) {
$result[$k]['user_info'] = $v;
$group = $this->model_users->getUserGroup($v['id']);
$result[$k]['user_group'] = $group;
}
$this->data['user_data'] = $result;
$this->render_template('users/index', $this->data);
}
Here you go
$this->db->select("ug.*,g.*");
$this->db->from("user_group ug");
$this->db->join('groups g', 'ug.user_id = g.group_id');
$this->db->where("ug.user_id",1);
$query = $this->db->get();
if ($query->num_rows() > 0) {
$result = $query->result();
} else {
$result = null;
}
return $result;

Codeigniter : update records if records exists there or then insert new records

In my Table i have four columns .
r_id
id (User id)
v_id (company id)
rate
All i am doing is to rate the company (v_id) from user.
Suppose, if user one is rate the 1st Company (v_id),Again when same user rate the same Company Then rate column automatically updated. if user one wants to rate another company then a new row will be added in the table. But in my case
when same user again rate the company then new row is inserted in the table.
Model
I don't know where i am doing wrong in this Model.
function ratings($insert,$id,$update,$v_id) {
// $this->db->where('id',$id);
// $this->db->where('v_id',$v_id);
// $run = $this->db->get('user_ratings');
// if ($run->num_rows() >= 1) {
// $this->db->where('id',$id);
// $this->db->update('user_ratings',$update);
// }else {
// // $this->db->set('user_id', $id);
// $this->db->insert('user_ratings',$insert);
// }
$query = $this->db->query('select id, v_id from user_ratings where id = "'.$id.'" and v_id = "'.$v_id.'"')->num_rows();
if ($query > 0) {
$this->db->query('update user_ratings set rate ="'.$update.'" where id = "'.$id.'"');
}else {
$this->db->insert('user_ratings',$insert);
}
}
Controller
function ratings() {
$id = $this->session->userdata('id');
$v_id = $this->uri->segment(3);
$insert= array (
'rate' => $this->input->post('click_val'),
'date' => date('Y-m-d H:i:s'),
'v_id' => $this->input->post('company_id'),
'id' => $this->input->post('id')
);
$update = array (
'rate' => $this->input->post('click_val'),
'date' => date('Y-m-d H:i:s'),
);
$this->Visa_mdl->ratings($value,$id,$update,$v_id);
}
Your on the right track. These simple changes should do the job.
Model
function ratings($data, $id, $v_id)
{
$query = $this->db->query("select r_id from user_ratings where id = $id and v_id = $v_id");
if($query->num_rows() > 0)
{
$data['r_id'] = $query->row()->r_id;
return $this->db
->where('id', $id)
->where('v_id', $v_id)
->update('user_ratings', $data);
}
else
{
return $this->db->insert('user_ratings', $data);
}
}
The method returns true or false to indicate the outcome.
Your controller modified to work with the above
function ratings()
{
$id = $this->session->userdata('id');
$v_id = $this->input->post('company_id');
$data = array(
'rate' => $this->input->post('click_val'),
'date' => date('Y-m-d H:i:s'),
'v_id' => $v_id,
'id' => $id
);
$this->Visa_mdl->ratings($data, $id, $v_id);
}
You have putted static value of v_id column try by replacing v_id ="2" with v_id = "'.$v_id.'" hope this will help you.
<?php
function ratings($insert,$id,$update,$v_id) {
$query = $this->db->query('select id, v_id from user_ratings where id = "'.$id.'" and v_id = "'.$v_id.'"')->num_rows();
if ($query > 0) {
$this->db->query('update user_ratings set rate ="'.$update.'" where id = "'.$id.'"');
}else {
$this->db->insert('user_ratings',$insert);
}
}

codeigniter join query issue in email

My Codeigniter join query is not work. In a function just try to match RC code in users table and get email, this function is properly work, next target is match email id from article table and get article its work properly, but ill try to join the users table and article table beacause i need to get the users firstname & lastname from users table, I don't know is that right way or not, check my code below. Controller Part :
public function user_article()
{
$rc=$_GET['rc'];
$data['title'] = "User Article";
if ($this->session->userdata ('is_logged_in')){
$data['profile']=$this->model_users->profilefetch();
$data['results']=$this->article_m->u_article($_GET);
$this->load->view('sd/header',$data);
$this->load->view('sd/user_article', $data);
$this->load->view('sd/footer', $data);
}
else {
}
}
My Model :
function u_article($rc)
{
$query=$this->db->select('email')->where('rc',$rc['rc'])->get('users');
$result=$query->result_array();
if ($query->num_rows() > 0) {
$row = $query->row_array();
$array = array ('email' => $row['email'], 'a.status' => '1');
$query1=$this->db->select('a.id,title,a.status,description,image,a.email,tags,postdate,firstname,lastname,rc')->join('users u','u.email = a.email','left')->where($array)->get('articles a');
if ($query1->num_rows() > 0) {
foreach ($query1->result() as $row) {
$data[] = $row;
}
return $data;
}
else {return NULL;}
} else {return NULL;}
}
check my code and tell me my mistakes Thanks in advance.
Error Shoe in View :
A Database Error Occurred
Error Number: 1052
Column 'email' in where clause is ambiguous
SELECT `a`.`id`, `title`, `a`.`status`, `description`, `image`, `a`.`email`, `tags`, `postdate`, `firstname`, `lastname`, `rc` FROM (`articles` a) LEFT JOIN `users` u ON `u`.`email` = `a`.`email` WHERE `email` = 'admin#gmail.com' AND `a`.`status` = '1'
Filename: F:\wamp\www\project\system\database\DB_driver.php
Line Number: 331
Refactored your code. Just copy-paste and check its working.
Controller:
public function user_article()
{
$rc = $this->input->get('rc');
$data['title'] = "User Article";
if ($this->session->userdata ('is_logged_in'))
{
$data['profile']=$this->model_users->profilefetch();
$data['results']=$this->article_m->u_article($rc);
$this->load->view('sd/header',$data);
$this->load->view('sd/user_article', $data);
$this->load->view('sd/footer', $data);
}
else
{
}
}
Model:
function u_article($rc)
{
$query = $this->db->select('email')->where('rc',$rc)->get('users');
$result = $query->result_array();
if ($query->num_rows() > 0)
{
$row = $query->row_array();
$array = array ('u.email' => $row['email'], 'a.status' => '1');
$query1 = $this->db->select('a.id,a.title,a.status,a.description,a.image,a.email,a.tags,a.postdate,u.firstname,u.lastname,u.rc')->join('users u','u.email = a.email','left')->where($array)->get('articles a');
if ($query1->num_rows() > 0)
{
foreach ($query1->result() as $row)
{
$data[] = $row;
}
return $data;
}
else {return NULL;}
} else {return NULL;}
}

PDO/MySQL fetch multiple columns with if statement

I'm currently trying to fetch two images location from my database, how do I return both columns and if both empty then echo another image. This is what I've got so far.
How do I return both photo and photo_small so that I may echo them in a php file.
PUBLIC FUNCTION Profile_Pic($uiD) {
$sth = $this->db->prepare("SELECT photo,photo_small FROM users WHERE uiD = :id");
$sth->execute(array(':id' => $uiD));
if ($sth->rowCount() > 0) {
$data = $row['photo'];
return $data;
} else {
$data = './icons/users.png';
return $data;
}
}
PUBLIC FUNCTION Profile_Pic($uiD) {
$sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($uiD));
$data = $sth->fetch();
if (empty($data['photo'])) {
$data['photo'] = './icons/users.png';
}
if (empty($data['photo_small'])) {
$data['photo_small'] = './icons/users.png';
}
return $data;
}
if you want to replace both images if even one is absent
PUBLIC FUNCTION Profile_Pic($uiD) {
$sql = "SELECT photo,photo_small FROM users WHERE uiD = ?";
$sth = $this->db->prepare($sql);
$sth->execute(array($uiD));
$data = $sth->fetch();
if (empty($data['photo']) || empty($data['photo_small'])) {
$data['photo'] = './icons/users.png';
$data['photo_small'] = './icons/users.png';
}
return $data;
}
Just return all of the values you want in an array.
You can ensure that both photo and photo_small are not empty strings or NULL by using empty().
Don't forget to retrieve your row using PDOStatement::fetch().
You should not use rowCount() to determine the number of rows returned in a SELECT statement. According to the documentation for PDOStatement::rowCount():
For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement.
Try this:
$row = $sth->fetch(PDO::FETCH_ASSOC);
if ($row && !empty($row['photo']) && !empty($row['photo_small'])) {
$data = array('photo' => $row['photo'], 'photo_small' => $row['photo_small']);
return $data;
} else {
$data = array('photo' => './icons/users.png', 'photo_small' => './icons/users.png');
return $data;
}
Then when you call the function, your returned result can be used like this:
$uiD = 1;
$result = Profile_Pic($uiD);
$photo = $result['photo'];
$photo_small = $result['photo_small'];

Categories