How to run join query in codenighter - javascript

hi i am new to codenighter frame work soome one can help me that how can i convert this join query to codenighter frame work and also told me that where i have to kept the join query i mean in model or controller..?
and how can i fetch the result of this query ..?
i want to pass the class_id as parameter..?
my query is here ..
SELECT e.roll,s.name,p.title,i.amount,i.amount_paid,i.status,i.creation_timestamp
FROM `payment` p
INNER JOIN student s ON s.student_id=p.student_id
INNER JOIN enroll e ON e.student_id=p.student_id
INNER JOIN invoice i ON i.student_id=p.student_id AND e.class_id=6 AND e.year="2016-2017"

You need to keep this SQL query in your model and then pass the result to controller. You can pass the result set to controller from model and can use it from there. If you wan to pass it to view then you need to pass its data variable into view variable.
it should be like this,
In MODEL File:
function get_data(){
$this->db->select('enroll.roll,student.name,payment.title,invoice.amount,invoice.amount_paid,invoice.status,invoice.creation_timestamp');
$this->db->from('payment');
$this->db->join('student', 'student.student_id = payment.student_id', 'inner');
$this->db->join('enroll', 'enroll.student_id = payment.student_id', 'inner');
$this->db->join('invoice', 'invoice.student_id = payment.student_id', 'inner');
$this->db->where(array('enroll.class_id'=>6,'enroll.year'=>'2016-2017'));
$query = $this->db->get();
if($query->num_rows()>0){
return $query->result_array();
}
}
In CONTROLLER you can call this model function like this:
$data['Data'] = $this->student_model->load_countries();
$this->load->view('student_data',$data);
This is as per CodeIgniter active record framework. Hope this will help you.

you can use query method to write your own query .
in query method you can use joins easily
for example
Your Model
class Model_name extends CI_Model {
function __construct()
{
parent::__construct();
}
public function get_record(){
$data = $this->db->query('
SELECT e.roll,s.name,p.title,i.amount,i.amount_paid,i.status,i.creation_timestamp
FROM `payment` p
INNER JOIN student s ON s.student_id=p.student_id
INNER JOIN enroll e ON e.student_id=p.student_id
INNER JOIN invoice i ON i.student_id=p.student_id AND e.class_id=6 AND e.year="2016-2017"
');
if($data->num_rows()>0){
return $data;
}
}
}

$this->db->join() is helper funtion to perform join query
Permits you to write the JOIN portion of your query:
$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();
// Produces:
// SELECT * FROM blogs JOIN comments ON comments.id = blogs.id
Multiple function calls can be made if you need several joins in one query.
If you need a specific type of JOIN you can specify it via the third parameter of the function. Options are: left, right, outer, inner, left outer, and right outer.
$this->db->join('comments', 'comments.id = blogs.id', 'left');
// Produces: LEFT JOIN comments ON comments.id = blogs.id
You can directly write query in the query() function too.
$query = $this->db->query('SELECT e.roll,s.name,p.title,i.amount,i.amount_paid,i.status,i.creation_timestamp
FROM `payment` p
INNER JOIN student s ON s.student_id=p.student_id
INNER JOIN enroll e ON e.student_id=p.student_id
INNER JOIN invoice i ON i.student_id=p.student_id AND e.class_id=6 AND e.year="2016-2017"');
References: CodeIgniter Docmentation

Refer:-https://www.codeigniter.com/userguide3/database/query_builder.html
You can also use below style:-
In MODEL File:
function get_data(){
$this->db->where(array('enroll.class_id'=>6,'enroll.year'=>'2016-2017'));
$this->db- >select('enroll.roll,student.name,payment.title,invoice.amount,invoice.amount_paid,invoice.status,invoice.creation_timestamp');
$query = $this->db->from('payment')->join('student', 'student.student_id = payment.student_id', 'inner')->join('enroll', 'enroll.student_id = payment.student_id', 'inner')->join('invoice', 'invoice.student_id = payment.student_id', 'inner')->get();
if($query->num_rows()>0){
return $query->result_array(); //You can also use result(); provide object array
}
}
In CONTROLLER you can call this model function like this:
$data['Data'] = $this->student_model->load_countries();
$this->load->view('student_data',$data);
In view you can get this with $data variable

Related

send data from php array in javascript forEach loop to url of ajax call

I'm trying to loop through the results of a mysql query in php, the output of the query is an array similar to [10201,10202]. I want to take the results and loop it to the variable named id in my javascript function and loop it through the url of my ajax call. The goal is to take the id and use it in a sql query on another page to change the date of the id in our database.
mysql query:
<?php
// sql query for # print all open orders function
$sql = "SELECT Order_PID
FROM `Order`
WHERE SHIPDATE IS NULL
AND Address1 IS NOT NULL;";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($query)) {
$order[] = $row['Order_PID'];
}
?>
javascript function:
I'm trying to use a forEach function to iterate through the results of the array.
$('button#printOpenOrders').on('click', function(e) {
if(confirm("Are you sure you want to print all open orders and mark them as pending?")) {
e.preventDefault();
// prints all open orders
window.open("/resources/scripts/allOpenPDF.php");
var arr = $order;
arr.forEach(function(id) { // <====this function
$.ajax({
url: "/resources/scripts/pending-order.php?id=" + id, // <===this variable
datatype : "string",
success : function(data) {
location.reload(true);
}
})
})
}
});
and if it helps here is my callback script
<?php
// login validation
session_start();
if (!isset($_SESSION['loggedin']) && $_SESSION['loggedin'] != true) {
$url = $_SERVER['DOCUMENT_ROOT'].'/index.php';
header("Location: ../../index.php");
}
// establish connection to database
include $_SERVER['DOCUMENT_ROOT'].'/resources/scripts/dbconnect.php';
$conn = openConnection();
// capture id
$id = $_GET['id'];
$pendingDate = date_create_from_format("m/d/Y", "07/26/1996");
$pendingDate = date_format($pendingDate, "Y-m-d H:i:s");
$sql = $conn->prepare("UPDATE `Order`
SET SHIPDATE = ?
WHERE Order_PID = ?");
$sql->bind_param("si", $pendingDate, $id);
$sql->execute();
echo "success";
closeConnection($conn);
?>
If parts of my code don't make sense, I'm new to this and I am using my currently limited knowledge to frankenstein all of this together. Any nudges in the right direction would be super helpful.
You can output $order variable contents, but you need to use PHP and also you must encode it using json format, so this could actually work:
var arr = <?PHP echo json_encode($order); ?>;
But it is error-prone, the syntax is not really nice to read, and if that variable somehow becomes in the format you are not expecting it could lead to another JavaScript syntax error.
But the best way in my opinion would be to make an AJAX request and get those order IDS, and after that you could create another AJAX request that would send all those Order IDS,
so you wouldn't need .forEach stuff and your logic of handling multiple orders need to be modified in order to accommodate for these changes.
But since you already have those IDS in PHP I mean stored in $order variable, you could just encode it and send it all the ids at once in a single request.

how to get string 'Sugar&Jaggery, Salt' via <a> in codeigniter?

plz anyone me i m beginner in codeigniter in herf passing url with string but the whole can't get in
controller & can't accepting as sting so what shold i do for it plz someone help me
//Here is html code which pass sting value
index.php/Home/product_show?type='Sugar&Jaggery , Salt'">Sugar & Jaggery , Salt
//controller get sting in type variable but on Sugur got not whole sting and pass type variable to model
public function product_show(){
$type = $_GET['type'];
die(var_dump($type));
$data['testdata']= $this->Globle_model->get_multiple_record($type);
$this->load->view('display_product',$data);
}
//model type variable check the subcategory from database and return to controller
public function get_multiple_record($type){
$this->db->where_in('Subcategory_name',$type);
$get_data = $this->db->get('productmaster');
return $get_data->result_array();
}
//o/p
get this much of string(6) "'Sugar"
Please follow the below way to get all your string into the controller into
$_GET['type'] variable.
Combine all your strings into a single variable using _ into href
Example :
Sugar & Jaggery , Salt
In the controller, I have created one array() with variable subcategory_type .In which key is coming from the view but its value from the database.
Example :
function get_product_type(){
$get_info = $this->input->get();
$subcategory_type = array(
"Sugar_Jaggery_Salt" => "Sugar&Jaggery , Salt"
);
$type_arr = $subcategory_type[$get_info['type']];
$data['testdata']= $this->Globle_model->get_multiple_record($type_arr);
$this->load->view('display_product',$data);
}
In model,
function get_multiple_record($type_array){
$this->db->where_in('Subcategory_name',$type_array);
$get_data = $this->db->get('productmaster');
return $get_data->result_array();
}
Try this and update me in case of anything.

Save results from pdo query to a javascript variable

I am new to javascript so please be patient with me.
I have a function in php which goes like this:
public function getSubjects() {
$stmt = $this->_db->prepare('SELECT id, subject from subjects');
$stmt->execute();
return $stmt->fetchall();
}
Then I have a variable subs in javascript which is hardocded like this:
var subs = {"Maths":1,"Geography":2,"Chmesitry":3,"Literature":4};
How do I populate the subs variable with the format above from the getSubjects method?
I like to use json_encode to convert the array to json so it can be used as an array of objects in JS.
PHP:
public function getSubjects() {
$stmt = $this->_db->prepare('SELECT id, subject from subjects');
$stmt->execute();
return json_encode($stmt->fetchall());
}
In javascript:
var subs = <?php echo getSubjects(); ?>;
console.log(subs);

How to put a string to make a query using PHP CodeIgniter

I have different strings that is made by multiple checkboxes when is checked and I would like to use this strings to make a query.
For example:
If I click a specific sequence of checkboxes this returns me this value of string: "SELECT Call_Setup FROM lte_kpi.vw_main_kpis_cidade_rate_daily WHERE node != 'UNKNOWN' and node = 'ABADIA DE GOIÁS' and date between '10/02/2017' and '10/18/2017' order by date"
I save this query into a variable called query1. What I would like is to put this variable (query1) like parameter to perform a query.
This is my model:
<?php
class Model_KPI_Customize extends CI_Model{
function kpi_customize_CustomQuery(){
$query = $this->db->query(/*I would like to put my string here !*/);
return $query->result();
}
}
?>
This is my Controller
public function highcharts_teste(){
$this->load->model('model_kpi_customize');
$data['kpi_customize_string_CustomQuery'] = $this->model_kpi_customize
->kpi_customize_CustomQuery();
}
And I have a view with multiple checkboxes and one paragraph element wich I would like to display the result of a query.
In the example above I would like to return the following values like this, because this is the result when I query it on Database:
99.73
99.48
99.51
99.40
99.23
99.34
99.29
99.10
99.23
99.11
Thanks everyone.
Bye =)
SELECT Call_Setup
FROM
lte_kpi.vw_main_kpis_cidade_rate_daily
WHERE
node != 'UNKNOWN' and
node = 'ABADIA DE GOIÁS' and
date between '10/02/2017' and '10/18/2017'
order by date
Can be written using active_record like below
$where = array(
'node' => 'ABADIA DE GOIÁS',
'date >=' => '10/02/2017',
'date <=' => '10/18/2017'
);
$this->db->select('Call_Setup')
->get_where('vw_main_kpis_cidate_rate_daily', $where )
->order_by("date", "asc");

generating multidimensional object with array

I am generating an object like this:
As you can see education is an array inside an object,
but what I want is for degree_1 and major_1 and their values to be in the same object.
This is how I want it but with education as an array:
One other thing:
When I var_dump it in my php it is just fine with the arrays and everything. But my javascript gets the second image above- object of object when it was just an array..
public function show($id)
{
$tmp = array();
$post = array();
$postInfo = Post::find($id);
$params = DB::select( DB::raw("SELECT param.*, sys_param_values.*,param_value.*,type_post.*,
param.name AS paramName,
doc_param.name AS docParamName
FROM param
LEFT JOIN doc_param ON param.doc_param_id = doc_param.id
LEFT JOIN sys_param_values ON param.id = sys_param_values.param_id
LEFT JOIN param_value ON sys_param_values.value_ref = param_value.id
LEFT JOIN type_post ON sys_param_values.ref_id = type_post.id WHERE type_post.id = ".$id));
$isMultiple = false;
$post['postInfo'] = $postInfo['original'];
foreach($params as $k=>$v) {
$iteration = $v->iteration;
$docParamName = $v->docParamName;
$paramName = $v->paramName;
if($v->value_ref == null) {
$value = $v->value_short;
} else {
$value = $v->value;
}
if($iteration) {
$post[$docParamName][$iteration][$paramName] = $value;
// need to return education as array not as object
// $post[$docParamName][] = array($paramName=>$value) ;
}elseif(!$iteration) {
$post[$docParamName][$paramName] = $value;
}
}
return Response::json($post);
}
Make first element from education to 0, now it is 1, so that's why json_encode is parsing it as an object.
I don't know what you data source looks like, but it looks to me that you're fetching vertical data and them want to display it horizontally. If that is the case your data need to be stored in a way that simply looping is enough, if not some PHP logic will be required.
We can't really help you on that until you show us an example of your table contents.
Cheers

Categories

Resources