Select Query in Group of 10 - php

I followed one link here, and modified my code accordingly. What I am trying to do achieve is for example a table name media_ids contains 45 rows(which is dyanamic), I want to divide the no of rows in a group of 10 rows minimum (in my case four groups of 10 rows and 1 group of 5) and execute code of each group per hour.
For example from select record from id 1 to 10 then second hour from 11 to 20 and so on unless fetches the last record and start again from id 1.
I added a tracker, which check whats the current limit and proceed.But its giving me the required result what I am trying to achieve.
<?php
require('inc/dbConnect.php');
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointer10=$lastPointer+10;
$currentMediaQuery = "select * from media_ids where id > ".$lastPointer." limit ".$lastPointer.",".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
if ($lastPointer + 10 > 40) {
$lastPointer = 1;
} else {
$lastPointer += 10;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");
?>

I am assuming you are calling this script every hour via ajax/Js...
In your code if you delete some data from another script you may find your first row id i.e 100 !
require('inc/dbConnect.php');
$limit = 10 ;
$lastPointerq = "select tracker from media_tracker";
$lastPointerResult = mysqli_query($con, $lastPointerq);
$lastPointerRes = mysqli_fetch_row($lastPointerResult);
$lastPointer = $lastPointerRes[0];
$lastPointerRes = mysqli_fetch_assoc($lastPointerResult);
$lastPointer = empty($lastPointerRes['tracker']) ? 0 : $lastPointerRes['tracker'] ;
$lastPointer10=$lastPointer* $limit;
$currentMediaQuery = "select * from media_ids limit ".$limit." OFFSET ".$lastPointer10."";
$mediaQuery = mysqli_query($con, $currentMediaQuery);
if (mysqli_num_rows($mediaQuery) > 0) {
while ($row = mysqli_fetch_assoc($mediaQuery)) {
// do stuff…
echo $id=$row['id']."<br>";
}
}
else
{echo "0";}
//do a total row count query here and set as value of $total rather than 40
$total =40 ;
$flag = ceil($total/$limit);
if ($lastPointer == $flag) {
$lastPointer = 0;
} else {
$lastPointer ++;
}
mysqli_query($con, "update media_tracker set tracker = $lastPointer");

Related

do while loop php with multiple conditions

I am posting full code here for make my situation more clear.
<?php
require '../includes/env.php';
require '../includes/db.inc.php';
$total_campaigns = 0;
$total_checked_campaigns = 0;
$checked_campaigns_ids ="0";
$current_campaign_id = 0;
$c_rull = 1;
$c_daily_limit = 0;
/*get all live campaigns count*/
$total_campaigns = get_total_campaigns($conn);
/*check if any campaign available for send data*/
if($total_campaigns>0){
do {
//get one campaign id from all available campaigns.
$c_id = get_campaign($total_campaigns,$total_checked_campaigns,$checked_campaigns_ids,$current_campaign_id,$conn);
/*this while loop is checking that selected campaign have reached daily limit or not,if above campaign id reached limit, it should get another possible campaign id, if there no any campaign id avaialble
get_campaign function will return 0 and we will stop the loop*/
} while(!(($c_id == 0 || $total_checked_campaigns <= $total_campaigns) && is_daily_limit_allow($c_id,$c_daily_limit,$conn)));
echo $c_id;
}
function get_campaign($total_campaigns,$total_checked_campaigns,$checked_campaigns_ids,$current_campaign_id,$conn){
$c_status = 1;//live
$c_lead_status = 0;//not processed
$selectCampaignQuery = "SELECT * FROM tbl_software_campaigns WHERE c_lead_status = ? AND c_status = ? AND c_id > ? AND c_id NOT IN($checked_campaigns_ids) ORDER by c_id ASC LIMIT 1";
$stmt = $conn->prepare($selectCampaignQuery);
$stmt->bind_param("iii", $c_lead_status,$c_status, $current_campaign_id);
$stmt->execute();
$selectCampaignResult = $stmt->get_result();
if ($selectCampaignResult->num_rows==0) {
if($total_checked_campaigns==0){
$update_campaigns_query = "UPDATE tbl_software_campaigns SET c_lead_status = 0 WHERE c_status = 1";
$update_campaign_result = mysqli_query($conn,$update_campaigns_query);
$selectCampaignQuery = "SELECT * FROM tbl_software_campaigns WHERE c_lead_status = ? AND c_status = ? AND c_id > ? AND c_id NOT IN($checked_campaigns_ids) ORDER by c_id ASC LIMIT 1";
$stmt = $conn->prepare($selectCampaignQuery);
$stmt->bind_param("iii", $c_lead_status,$c_status, $current_campaign_id);
$stmt->execute();
$selectCampaignResult = $stmt->get_result();
}
}
if ($selectCampaignResult->num_rows>0) {
global $total_checked_campaigns;
global $c_daily_limit;
global $checked_campaigns_ids;
$row = mysqli_fetch_assoc($selectCampaignResult);
$c_id = $row['c_id'];
$c_daily_limit = $row['c_daily_limit'];
// we are updating total checked campaign count here as well updating comma seperated list of checked campaign id here in below two line
$total_checked_campaigns = $total_checked_campaigns+1;
$checked_campaigns_ids = $checked_campaigns_ids.",".$c_id;
//return campaign id for process the data
return $c_id;
}else{
//return 0 because there no any campaign available to process data
return 0;
}
}
function get_total_campaigns($conn){
$stmt = $conn->prepare("SELECT COUNT(c_id) AS total_campaigns FROM tbl_software_campaigns WHERE c_status = 1");
$stmt->execute();
$total_result = $stmt->get_result();
$row = mysqli_fetch_assoc($total_result);
$stmt->close();
return $row['total_campaigns'];
}
function is_duplicate($EMAIL,$conn){
$query = "SELECT lead_id FROM tbl_software_leads WHERE lead_email = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $EMAIL);
$stmt->execute();
$duplicate_result = $stmt->get_result();
$stmt->close();
if ($duplicate_result->num_rows>0){
return true;
}else{
return false;
}
}
function is_daily_limit_allow($CAMPAIGN,$LIMIT,$conn){
if($LIMIT>0){
$limit_query = "SELECT count(*) as today_total FROM tbl_software_leads WHERE DATE(lead_time)=CURDATE() AND lead_camp_id =? AND lead_status = 1";
$stmt = $conn->prepare($limit_query);
$stmt->bind_param('i',$CAMPAIGN);
$stmt->execute();
$limitrow = $stmt->get_result()->fetch_assoc();
$todaysrecord = $limitrow['today_total'];
if($todaysrecord<$LIMIT){
return true;
}else{
return false;
}
}else{
return true;
}
}
?>
Now Let me explain my goal.
What I am looking to do is
on start its checking how many campaigns available there!
if campaign available more than 0, I am getting one campaign id and marking that campaign as checked campaign using get_campaign function
get_campaign function giving me campaign id and if there no any campaign available for process, its give me 0 as id.
if there 0 as id, I do not want do anything since it means there no any campaign available for handle the data
if get_campaign give me any campaign id, I need to check that its reached daily limit or not with is_daily_limit_allow function, if its reached that limit, I need to get new id using get_campaign function and check its daily limit.
I am trying to achieve above thing with while loop but its not working properly and running for infinity time.
Basically when
if campaign id is 0, I want stop the loop
if total checked campaigns equal to total campaigns, I want stop the loop because it means we have checked all campaigns and none are available for process the data
if current campaign id allow to process data and have not daily limit, I want stop the loop.
I should also clear that when
$c_daily_limit = 0;
means there no any daily limit in that campaign.
I hope its clear everything now and will help to expert here on stackoverflow.
Let me know if anyone can help me for solve the puzzle.
Thanks!
You said
if campaign id is 0, I want stop the loop
if total checked campaigns equal to total campaigns, I want stop the loop because it means we have checked all campaigns and none are
available for process the data
if current campaign id allow to process data and have not daily limit, I want stop the loop.
So, it makes straightforward conditions as below,
while($c_id != 0 && $total_checked_campaigns < $total_campaigns && is_daily_limit_allow($c_id,$c_daily_limit,$conn));
Try below snippet once
do {
echo $c_id;
echo "<br>";
$c_id = get_campaign($total_campaigns);
} while (($c_id == 0 || $total_checked_campaigns <= $total_campaigns) && is_daily_limit_allow($c_id));
here I changed condiotions as per your trying to get
(($c_id == 0 || $total_checked_campaigns <= $total_campaigns) && is_daily_limit_allow($c_id))
as i understand can you try this code
do {
echo $c_id;
echo "<br>";
$c_id = get_campaign($total_campaigns);
} while (($c_id != 0 && $total_checked_campaigns <= $total_campaigns) || !is_daily_limit_allow($c_id));
or
while(!(($c_id == 0 || $total_checked_campaigns <= $total_campaigns) && is_daily_limit_allow($c_id)))

Duplication in serial number while generating tickets

I'm trying to generate barcode tickets after successful booking and it's working fine. But yesterday (06-Jan-2017) night at 11.59 pm, one customer booked 2 tickets but the ticket sl.no was duplicate. Tthat is both tickets sl.no was 1. Actually it should be 2. But the next customer's tickets sl.no was correct, it's 3,4,5. Is there any mistake in the code below where the tickets get generated?
for($j=1;$j<=$cat_array[$i];$j++) {
$sel_max_dt = mysql_query("select MAX(DT) AS maxdt, MAX(REC_NO) AS maxrec FROM tkt_barcode");
//to select max date and max rec no.
$row_max_dt = mysql_fetch_array($sel_max_dt);
$dt_max = $row_max_dt['maxdt'];
//$no_max = $row_max_dt['maxno'];
$recno = $row_max_dt['maxrec'];
if($dt_max == date("Y-m-d") && $recno == $TxnID) {
//if same date and same bkid barcode slno continues.
$sel_no = mysql_query("select MAX(BARCODE_SLNO) AS maxno FROM tkt_barcode WHERE REC_NO=".$TxnID);
$row_sel_no = mysql_fetch_array($sel_no);
$tkt_slno = $row_sel_no['maxno'];
$tkt_slno = $tkt_slno + 1;
}
if($dt_max == date("Y-m-d")&& $recno != $TxnID) {
//if same date and different bkid barcode slno continues.
$sel_no = mysql_query("select MAX(BARCODE_SLNO) AS maxno FROM tkt_barcode WHERE DT='$dt_max' ");
$row_sel_no = mysql_fetch_array($sel_no);
$tkt_slno = $row_sel_no['maxno'];
$tkt_slno = $tkt_slno + 1;
}
if($dt_max != date("Y-m-d") && $recno != $TxnID) {
//if not same date start barcode slno from 1.
$tkt_slno = 1;
}
$sel_sl_no = mysql_query("select MAX(SL_NO) AS slno FROM tkt_barcode WHERE REC_NO=".$TxnID);
$row_slno = mysql_fetch_array($sel_sl_no);
$slno = $row_slno['slno'];
$bartkt_slno = $slno + 1;
if($i==1 && $j>$count_promo_adult && $arr_edit["PROMO_CODE"]!=""){
//adult cat and total adult count > total promo adult count
$disc_adult = $adult_amt;
$discamt=$adult_amt - $disc_adult ; // discount amt
$rate=$adult_amt; //normal rate
$net_amt=$disc_adult; //discount rate
$pro_cd ="";
//promo code is null when total adult count > total promo adult count
} //end if
//string pading digits
$len_txn =strlen($TxnID); // bookid length
$pad = 6; //str_pad digits
if($len_txn > 5) {
if($len_txn==6) { $pad = $pad-1;}// if 6 digit
if($len_txn==7){ $pad = $pad-2;}// if 7 digit
}
$fullbar = $TxnID.str_pad($tkt_slno, $pad, 0, STR_PAD_LEFT).$clnd_date.$counter_no;
//barcode no
$fields = "BARCODE_SLNO,DT,FIN_YEAR,Counter_Code,Branch_cd,REC_NO,BARCODE,TICKET_TYPE,CATG_CD,AMT,DISC_AMT,SL_NO,NET_AMT,BCODE_CATG_SLNO,BCODE_SLNO_GEN,BCODE_SLNO_CATG_TOT,DAY_TYPE,Check_in_date,PROMO_CODE,TAX,S_TAX,conv_base_rate,conv_tax_rate";
$values = "'$tkt_slno','$booked_date','$fin_year','$counter_no','$branch','$TxnID','$fullbar','$cat_name_tkt','$i','$rate','$discamt','$bartkt_slno','$net_amt','$j','$count','$cat_tot','$type_day','$date_check','$pro_cd','$tax_each','$ser_tax_each','$conv_base','$conv_tax'";
$sql_tkt = $objA->insert_fields(TABLEPREFIX.'tkt_barcode',$fields,$values);
}//end for loop
You are selecting a count of existing records
$sel_sl_no = mysql_query("select MAX(SL_NO) AS slno FROM tkt_barcode WHERE REC_NO=".$TxnID);
$row_slno = mysql_fetch_array($sel_sl_no);
$slno = $row_slno['slno'];
$bartkt_slno = $slno + 1;
and using that count to set your sl number. But time passes between reading the count and writing the record. When two threads read the count at the same time you get your problem.
Finally I found the solution by adding another condition given below.
if($dt_max != date("Y-m-d")&& $recno == $TxnID) {
//if different date and same bkid barcode slno continues.
$sel_no = mysql_query("select MAX(BARCODE_SLNO) AS maxno FROM tkt_barcode WHERE DT='$dt_max' ");
$row_sel_no = mysql_fetch_array($sel_no);
$tkt_slno = $row_sel_no['maxno'];
$tkt_slno = $tkt_slno + 1;
}
Thanks guys for the help. I will try to make my code more readable next time. :)

binary tree child counting php mysql

I am stuck in some situation where I have to count Left Child and Right Child of a Binary Tree My database structure is as under.
SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'"
Where rid is = referral id And pid = parent id,
I need to count all leaves of given parent id for example
if id 1 has left 2 and right 3 immediate childs i need to know total left member count and total right members count.
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ \
8 9 11
/ \
10 12
/ \
13 14
I need to count all childs of 1.
I am using this function but it is only counting most left please modified it or explain your own
function leftcount($id) //Function to calculate leftcount
{
$sql = "SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'";
$execsql = mysql_query($sql);
$array = mysql_fetch_array($execsql);
//var_dump($array);
(array_count_values($array));
if(!empty($array['l_mem']))
{
$count += leftcount($array['l_mem']);
}
$totalcount = 1 + $count;
return $totalcount ;
}
$left = leftcount($id);
doing -1 because in function 1 + $count.
$left = $left-1;
Please do not mark Duplicate or any other if you don't have solution
You need to use these 3 function to calculate the left right and all child of any element.
function leftcount($id) //Function to calculate all left children count
{
$sql = "SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'";
$execsql = mysql_query($sql);
$array = mysql_fetch_array($execsql);
(array_count_values($array));
$count = 0;
if(!empty($array['l_mem']))
{
$count += allcount($array['l_mem']) +1;
}
return $count;
}
function rightcount($id) //Function to calculate all right children count
{
$sql = "SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'";
$execsql = mysql_query($sql);
$array = mysql_fetch_array($execsql);
(array_count_values($array));
$count = 0;
if(!empty($array['r_mem']))
{
$count += allcount($array['r_mem']) +1;
}
return $count;
}
function allcount($id) //Function to calculate all children count
{
$sql = "SELECT id,usr_name,rid,pid,l_mem,r_mem,position,joining_date FROM user WHERE id = '$id'";
$execsql = mysql_query($sql);
$array = mysql_fetch_array($execsql);
(array_count_values($array));
$count = 0;
if(!empty($array['l_mem']))
{
$count += allcount($array['l_mem']) +1;
}
if(!empty($array['r_mem']))
{
$count += allcount($array['r_mem']) +1;
}
return $count;
}
If you pass 1 to these function. answer for these are as follows
echo leftcount(1); // 8
echo rightcount(1); // 5
echo allcount(1); // 13

PHP sorting array output

UPDATE 2 (Players Handicap Index Calculation)
$sql3 = "SELECT roundID FROM rounds WHERE userID='$userID'";
$result3 = mysql_query($sql3) or die(mysql_error());
$total_rounds = mysql_num_rows($result3);
//CALCULATE USER HANDICAP INDEX IF TOTAL_ROUNDS > 4
if($total_rounds > 4){
if($total_rounds<7) { $score_count = 1; }
elseif($total_rounds<9) { $score_count = 2; }
elseif($total_rounds<11) { $score_count = 3; }
elseif($total_rounds<13) { $score_count = 4; }
elseif($total_rounds<15) { $score_count = 5; }
elseif($total_rounds<17) { $score_count = 6; }
elseif($total_rounds<18) { $score_count = 7; }
elseif($total_rounds<19) { $score_count = 8; }
elseif($total_rounds<20) { $score_count = 9; }
else { $score_count = 10; }
$sql2 = "SELECT differential FROM rounds WHERE userID='$userID' ORDER BY date DESC LIMIT 20";
$result2 = mysql_query($sql2) or die(mysql_error());
$diff_results = array();
while($row = mysql_fetch_assoc($result2)){
$diff_results[] = $row['differential'];
}
sort($diff_results);
$diff_results = array_slice($diff_results, 0, $score_count);
$handicapIndex = array_sum($diff_results) / $score_count * 0.96;
$handicapIndex = (floor($handicapIndex * 10)) / 10;
Hopefully this will give you all and idea of how I calculate a players handicap index. Now I would like to show the player (user) the rounds (date ordered) that are used to calculate his index.
Always appreciative!
UPDATE (structure of rounds table)
roundID - auto incrementing primary key
userID - INT
courseID - INT
tee - VARCHAR
differential - FLOAT
date - DATE
I am struggling to even get started with this feature I am trying to implement. Any help would be much appreciated.
I have a set of mysql db results I would like to sort by field differential. I pull them out of the db like this:
$sql4 = "SELECT * FROM rounds WHERE userID='$userID' ORDER BY date DESC LIMIT 20";
$result4 = mysql_query($sql4) or die(mysql_error());
$total_rounds = mysql_num_rows($result4);
As you can see above I counted the rows returned to run through this if-elseif-else statement to figure out how many scores I need to highlight with different css:
if($total_rounds<7) { $score_count = 1; }
elseif($total_rounds<9) { $score_count = 2; }
elseif($total_rounds<11) { $score_count = 3; }
elseif($total_rounds<13) { $score_count = 4; }
elseif($total_rounds<15) { $score_count = 5; }
elseif($total_rounds<17) { $score_count = 6; }
elseif($total_rounds<18) { $score_count = 7; }
elseif($total_rounds<19) { $score_count = 8; }
elseif($total_rounds<20) { $score_count = 9; }
else { $score_count = 10; }
For example, if $total_rounds = 16 my $score_count would be 6.
Now I need to take this data set of 16 rows and spit it out with php so I maintain my ORDER BY date while applying a different css format to the 6 figured in the above if-elseif-else statement. The $score_count is figured because I need to highlight (aka apply different css) to the 6 lowest scores of the 16 row data set WHILE maintaining my date order.
The desired output would look like this (with the * denoting the separate css format *).
01-08-2013 - 16
01-07-2012 - 1 *
01-06-2013 - 15
01-05-2012 - 2 *
01-04-2013 - 14
01-03-2012 - 3 *
01-02-2013 - 13
01-01-2012 - 4 *
12-31-2012 - 12
12-30-2012 - 5 *
12-29-2012 - 11
12-28-2012 - 6 *
12-27-2012 - 10
12-26-2012 - 9
12-25-2012 - 8
12-24-2012 - 7
Please let me know if you have questions.
Thanks
There are couple of steps that you will have to follow.
1) Sort the results with score(differential) and get the ids of the six records having lowest score.
$sql4 = "SELECT * FROM rounds WHERE userID='$userID' ORDER BY differential LIMIT 20";
$result4 = mysql_query($sql4) or die(mysql_error());
$total_rounds = mysql_num_rows($result4);
if($total_rounds<7) { $score_count = 1; }
elseif($total_rounds<9) { $score_count = 2; }
elseif($total_rounds<11) { $score_count = 3; }
elseif($total_rounds<13) { $score_count = 4; }
elseif($total_rounds<15) { $score_count = 5; }
elseif($total_rounds<17) { $score_count = 6; }
elseif($total_rounds<18) { $score_count = 7; }
elseif($total_rounds<19) { $score_count = 8; }
elseif($total_rounds<20) { $score_count = 9; }
else { $score_count = 10; }
$idsArray = array();
for($i=0; $i<$score_count; $i++){
$dets = mysql_fetch_array($result4);
$idsArray[] = $dets['roundID'];
}
2) Loop over records and match the id in array that you have made by first step. If id matches apply CSS otherwise not.
$sql4 = "SELECT * FROM rounds WHERE userID='$userID' ORDER BY date DESC LIMIT 20";
$result4 = mysql_query($sql4) or die(mysql_error());
while($dets = mysql_fetch_array($result4)){
if(in_array($dets['roundID'], $idsArray)){
//apply CSS
//display details here
}
else{
//display details here
}
}
Note: You should stop using mysql_* now. Its highly recommended by experts to use mysqli_* instead
I will take your example of $total_rounds = 16 my $score_count would be 6.
$total_rounds = 16;
$score_count = 6 // comes from the if-else loop you already have
// now we loop over the result
// the css is applied to every odd result, until $score_count is not 0
$counter = 0;
while( ( $data = mysql_fetch_assoc( $result4 ) ) !== false ) {
if( ( $counter % 2 ) && $score_count ) {
echo $data['date']; // apply your css here
} else {
echo $data['date'];
}
$counter++;
$score_count--;
}
Hope this helps.

select with limit and update table. Limit not working fine. sql

I am trying to update thable with select using limit
It's update table fine when we enter "limit" only with one parameter in select query like (limit 50)
But when select with "limit" like (limit $sqlFrom, $sqlTo) it updates the table but skip 2nd (51 to 100) records and again start updating from 101.
It skip every 2nd 50 records
Where is the problem???
Here is the code
$sqlFrom = 0;
$sqlTo = 50;
for($try = 0; $try < 6; $try++)
{
$res = mysql_query("select * from table_name where underprocess = 0 limit " . $sqlFrom . "," . $sqlTo);
while($row = mysql_fetch_array($res))
{
$id = $row['id'];
mysql_query("update table_name set underprocess = 1 where id = " . $id) or die('error');
echo $id;
}
print '<hr/>';
if($sqlFrom != 0)
{
$sqlFrom += $sqlTo;
}
else
{
$sqlFrom = $sqlTo;
}
}//for
This is as expected
When you update rows 1-50 based on your first iteration, you set underprocess = 1. These are ignored in the 2nd call because ask for rows underprocess = 0.
So rows 51-100 in the 1st query are now rows 1-50 for your 2nd query if you like.
You don't need to change your LIMIT range because you always want the "first" 50.
NOTE
Your LIMIT isn't guaranteed anyway because you have no ORDER BY.

Categories