This is my simple query in mysql/zend:
// Get Patients
$table = new Model_Patient_DbTable();
$select = $table->select();
$select->from( 'patient' );
$select->setIntegrityCheck( false );
// insurance join
$select->joinLeft( 'insurance', 'patient.insuranceId=insurance.Id',
array( 'insName' => 'insName'));
// Get total no of records
$totalRecords = count( $table->fetchAll( $select ) );
// Filters
if( $inactive ) {
$select->where('patient.inactive = ?', $inactive );
}
// Other where clause conditions
// Fetch filtered patient records
$patientRecords = $table->fetchAll( $select );
// Get total no of filtered patient records
$filteredRecords = count( $table->fetchAll( $select ) );
In above zend query I am get getting patient records and their insurances based on some conditions in where clause. I have to get (1) Total No. of Records, (2) Total No. of filtered Records and also (3) Patient Records to show on webpage.
Problem is that in my above query I have to fetch records 3 times which slow the performance when there are 10,000 records. How can I optimize my query that it fetch the the records only once OR there should be a separate query for counting that will only get total No of records instead of fetching all records.
Every reply will be appreciated.
Thanks
Thanks
Something like this should get you started, unfortunately I don't have a way of testing this currently.
// Get Patients
$table = new Model_Patient_DbTable();
// Get Total records
$select = $table->select();
$select->from($table, array('COUNT(*) as row_count'));
$select->setIntegrityCheck(false);
$select->joinLeft('insurance', 'patient.insuranceId = insurance.Id', array('insName' => 'insName'));
$result = $table->fetchAll($select);
$totalRecords = $result[0]->row_count;
// Filters
if ($inactive) {
$select->where('patient.inactive = ?', $inactive);
}
// Get Total filtered records
$result = $table->fetchAll($select);
$filteredRecords = $result[0]->row_count;
// Get filtered records
$select = $table->select();
$select->from($table);
$select->setIntegrityCheck(false);
$select->joinLeft('insurance', 'patient.insuranceId = insurance.Id', array('insName' => 'insName'));
if ($inactive) {
$select->where('patient.inactive = ?', $inactive);
}
$patientRecords = $table->fetchAll($select);
Note: You may be able to re-use the same Zend_Db_Select object by overwriting the $select->from() to remove the COUNT(*) addition.
Related
I have one table based on which one I have to update 6 rows in the other table for matching ids. It is total of over 1000 records so most of the time I get timeout error with current script.
The way I do it now is, I select the range of ids between two dates from the first table, store it into an array and then run foreach loop making update in the second table where the ids are the same, so basically I run a query for every single id.
Is there anyway I could speed it up the process?
I found only a way to generate the each within the foreach loop
UPDATE product SET price = CASE
WHEN ID = $ID1 THEN $price1
WHEN ID = $ID1 THEN $price2
END
But I don't know how could I modify this to update multiple rows at the same time not just one.
My script code look like that
$sql = "SELECT * FROM `games` where (ev_tstamp >= '".$timestamp1."' and ev_tstamp <= '".$timestamp2."')";
while($row = mysqli_fetch_array($sql1)){
$one_of =[
"fix_id" =>$row['fix_id'],
"t1_res" =>$row['t1_res'],
"t2_res" =>$row['t2_res'],
"ht_res_t1" =>$row['ht_res_t1'],
"ht_res_t2" =>$row['ht_res_t2'],
"y_card_t1" =>$row['y_card_t1'],
"y_card_t2" =>$row['y_card_t2'],
"t1_corners" =>$row['t1_corners'],
"t2_corners" =>$row['t2_corners'],
"red_card_t1" =>$row['red_card_t1'],
"red_card_t2" =>$row['red_card_t2']
];
array_push($today_games,$one_of);
}
foreach($today_games as $key=>$val){
$cards_t1=$val['red_card_t1']+$val['y_card_t1'];
$cards_t2=$val['red_card_t2']+$val['y_card_t2'];
$sql = "Update sights SET t1_res='".$val['t1_res']."',
t2_res='".$val['t2_res']."', ev_tstamp='".$val['ev_tstamp']."',
ht_res_t1='".$val['ht_res_t1']."', ht_res_t2='".$val['ht_res_t2']."',
t1_corners='".$val['t1_corners']."',t2_corners='".$val['t2_corners']."',
t1_cards='".$cards_t1."',t2_cards='".$cards_t2."'
where fix_id='".$val['fix_id']."' "
}
Consider an UPDATE...JOIN query using fix_id as join column. Below runs mysqli parameterized query using timestamps. No loop needed.
$sql = "UPDATE sights s
INNER JOIN `games` g
ON s.fix_id = g.fix_id
AND g.ev_tstamp >= ? and g.ev_tstamp <= ?
SET s.t1_res. = g.t1_res,
s.t2_res. = g.t2_res,
s.ev_tstamp = g.ev_tstamp,
s.ht_res_t1 = g.ht_res_t1,
s.ht_res_t2 = g.ht_res_t2,
s.t1_corners = g.t1_corners,
s.t2_corners = g.t2_corners,
s.t1_cards = (g.red_card_t1 + g.y_card_t1),
s.t2_cards = (g.red_card_t2 + g.y_card_t2)";
$stmt = mysqli_prepare($conn, $sql);
mysqli_stmt_bind_param($stmt, 'ss', $timestamp1, $timestamp2);
mysqli_stmt_execute($stmt);
I have a query that requests an ID (the PK) and an order number and throws them into an array. I then loop through the returned data in the array and run two more queries to find the number of times the order number shows up in the database and to get the invoice numbers that belong to that order number. The problem I'm seeing with this setup is that it is taking a while (around 9 seconds) to return the compiled data array. Is there a faster way to get the returned results I'm looking for?
I've tried to find some articles online and came across mysqli_multi_query. Is this the better route to make multiple queries to gather the type of data I am trying to get?
<?php
require 'config.php';
$sql = "SELECT id,internal_order_number FROM orders GROUP BY internal_order_number ORDER BY created_date desc LIMIT 0 ,50";
$query=mysqli_query($mysqli, $sql);
if (!$query) {
throw new Exception(mysqli_error($mysqli)."[ $sql]");
}
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData['line_id'] = $row["id"];
$nestedData['internal_order_number'] = $row["internal_order_number"];
$data[] = $nestedData;
}
$compiled_data = array();
// Loop through data array with additional queries
foreach($data as $line){
$new_data = array();
// Get item counts
$item_counts = array();
$get_count = " SELECT internal_order_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."' ";
$count_query=mysqli_query($mysqli, $get_count);
while ($counts=mysqli_fetch_array($count_query)){
if (isset($item_counts[$counts['internal_order_number']])) {
$item_counts[$counts['internal_order_number']]++;
} else {
$item_counts[$counts['internal_order_number']] = 1;
}
}
$product_count = $item_counts[$line['internal_order_number']];
// Get invoice numbers
$invoice_array = array();
$get_invoices = " SELECT invoice_number FROM orders WHERE internal_order_number = '".$line['internal_order_number']."'";
$invoice_query=mysqli_query($mysqli, $get_invoices);
while ($invoice=mysqli_fetch_array($invoice_query)){
if(!in_array($invoice['invoice_number'], $invoice_array)){
$invoice_array[] = $invoice['invoice_number'];
}
}
$invoices = implode(", ",$invoice_array);
$new_data['order_number'] = $line['internal_order_number'];
$new_data['count'] = $product_count;
$new_data['invoices'] = $invoices;
$compiled_data[] = $new_data;
}
mysqli_close($mysqli);
print_r($compiled_data);
?>
What, why are you doing basically the same query 3 times. You first one selects them all, you second query requires the same table making sure the first tables order number == the tables order number and the last just grabs the invoice number...?
Just do one query:
SELECT internal_order_number, invoice_number FROM table WHERE ...
Then loop through it and do what you need. You don't need 3 queries...
I want to iterate the values of the array $code and $per_sectionfrom the query below. What looping method should i use? Or is this the right thing to do?
//total students
$count_query=mysql_query("select total_students from subject where teacherid = '$get_id'");
while($count_row=mysql_fetch_array($count_query)){
$total += $count_row['total_students'];
}
$query = mysql_query( "Select code,total_students from subject where teacherid='$get_id'");
while($result=mysql_fetch_assoc($query))){
$section = ($result['total_students']/ $total)*30;
$per_section[] = round($section, 0, PHP_ROUND_HALF_UP);
$code[] = $result['code'];
}
//perform this statement for a number of times depending on the number of array of $code..
$user_query=mysql_query("select * from result where subject_id ='$code' and faculty_id = '$get_id'LIMIT $per_section ")or die(mysql_error());
while($row=mysql_fetch_assoc($user_query)){
...
}
Sample data:
Subject table
code total_students teacherid
IT230 45 11-0009
IT213 44 11-0009
IT214 40 11-0009
result table
subject__id faculty_id
IT230 11-0009
IT213 11-0009
IT214 11-0009
Expected Results:
I want to show only 30 records of students that matches the result table.
Since the total students of that teacher are 45, 44, 40 = 129. This is the $per_section
IT230 only needed students = (45/129)*30 = 10.46 or i need only 11 of the results.
IT213 only needed students = (44/129)*30 = 10.23 or i need only 10 of the results.
IT214 only needed students = (40/129)*30 = 9.3 or i need only 9 of the results.
I want to search for the records in IT230 and select only 11 of them.
IT213 for only 10 and IT214 for 9. Since i only have 3 records, only these three records will show up.
As mentioned in the comments on your question, it is much better practice to use prepared statements via PDO and JOIN the two tables:
$dbh = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
$stmt = $dbh->prepare('
SELECT result.*
FROM result
JOIN student ON result.subject_id = student.code
WHERE student.id = :id
');
$stmt->execute(['id' => $id]);
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
Use one query that joins the two tables:
SELECT s.total_students, s.code, r.*
FROM students AS s
LEFT JOIN result AS r ON r.subject_id = s.code
WHERE s.teacher_id = '$get_id' AND r.faculty_id = '$get_id'
ORDER BY s.code
Then you can get all the information in a single loop:
while ($result = mysqli_fetch_assoc($query)) {
if (!isset($per_section[$result['code']]) {
$per_section[$result['code']] = round($result['total_student']/$total*30, 0, PHP_ROUND_HALF_UP);
$code[] = $result['code'];
}
if ($result['subject_id'] !== null) {
// do stuff with columns from result table here
}
}
I'm using codeigniter;
I would like to get last N rows from my table.
In my query I want to get last 200 rows:
$this->m_general->select('count(*)');
$this->m_general->from('pm');
$result_count_query = $this->m_general->get();
$count_query = $result_count_query->num_rows();
$data['all'] = $this->m_general->get('pm', array( 'admin_delete'=>0 ) , $count_query-200,$count_query, array('admin_seen'=>'asc' , 'id'=>'desc') );
but it returns nothing.
where is my wrong ?
updated
below query not worked fine and it returns all records :
$data['all'] = $this->m_general->get('pm', array( 'admin_delete'=>0 ) ,200, array('admin_seen'=>'asc' , 'id'=>'desc') );
This Solve the Problem
$query = $this->db->query("SELECT * FROM pm WHERE admin_delete= 0 AND admin_seen=0 ORDER BY id DESC LIMIT 200");
$result = $query->result_array();
$count = count($result);
if(empty($count))
{
echo 'array is empty';
}
else{
return $result;
}
Check out the API
https://ellislab.com/codeigniter/user-guide/database/active_record.html
Looks like you can't do this with the get method.
Build your query according to the API.
$this->m_general->limit(200);
$this->m_general->order_by("admin_seen", "asc");
$this->m_general->order_by("id", "desc");
$data['all'] =
$this->m_general->get('pm', array( 'admin_delete'=>0 ));
I have a simple table (mgap_orders) with customer orders in it. Multiple have the the same id (mgap_ska_id) and I simply want to pull 5 records from the table and display all five.
I can easily get one record with the following query and PDO, but how can I display 5 rows instead of only one row?
$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id";
while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
{
$item=$row_cat_sub['mgap_item_description'];
$item_num=$row_cat_sub['mgap_item_number'];
$item_type=$row_cat_sub['mgap_item_type'];
$item_cat=$row_cat_sub['mgap_item_catalog_number'];
$item_ven=$row_cat_sub['mgap_item_vendor'];
$item_pur=$row_cat_sub['mgap_item_percent_purchased'];
$item_sales=$row_cat_sub['mgap_item_sales'];
}
Use limit 5 then put the results in an array, like this:
$result_cat_item = "SELECT * FROM mgap_orders WHERE mgap_ska_id = '$id' GROUP BY mgap_ska_id LIMIT 5";
$items = array();
while($row_cat_sub = $stmt_cat_item->fetch(PDO::FETCH_ASSOC))
{
$items['item'] = $row_cat_sub['mgap_item_description'];
$items['item_num'] = $row_cat_sub['mgap_item_number'];
$items['item_type'] = $row_cat_sub['mgap_item_type'];
$items['item_cat'] = $row_cat_sub['mgap_item_catalog_number'];
$items['item_ven'] = $row_cat_sub['mgap_item_vendor'];
$items['item_pur'] = $row_cat_sub['mgap_item_percent_purchased'];
$items['item_sales'] = $row_cat_sub['mgap_item_sales'];
}
Then you can do:
foreach($items as $item) {
// echo $item['item'] or whatever
}
EDIT: Or you can skip putting them in the array and just use the while() to do what you need to do with the data.