PHP Script loops not working - php

I have the following script:
<?php
ini_set('max_execution_time', 0);
include("../includes/mysqli.php");
$pointsvar = 50000;
$inserts = 0;
$locationvar = 32000006;
while($locationvar <= 32000260){
while($pointsvar >= 20000){
$url = "http://185.112.249.77:9999/Api/Search?search=&level=0&min=1&max=50&points=$pointsvar&loc=$locationvar";
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$in=$data['clanList'];
$results = $data['results']; //max is 64
$i = 0;
while($i + 1 <= $results){
$clanid = $in[$i]['id'];
$clanname = mysqli_real_escape_string($con,$in[$i]['name']);
$clanplayerCount = $in[$i]['playerCount'];
$clanwarswon = $in[$i]['warsWon'];
$clanwarslost = $in[$i]['warsLost'];
$clanwarstied = $in[$i]['warsTied'];
$clanLocation = mysqli_real_escape_string($con,$in[$i]['clanLocation']);
$clanlevel = $in[$i]['level'];
$score = $in[$i]['score'];
$sql = "INSERT INTO activeclans(id, name, location, playercount, clanlevel, warswon, warslost, warstied, score)
VALUES('$clanid', '$clanname', '$clanLocation', '$clanplayerCount', '$clanlevel', '$clanwarswon', '$clanwarslost', '$clanwarstied', $score)";
mysqli_query($con, $sql);
$i++;
$inserts++;
}
$pointsvar = $pointsvar-500;
sleep(1);
}
$locationvar++;
sleep(1);
}
echo "Inserted $inserts";
?>
When I run it I am expecting it to go through each location and in each location I expect it to -500 from the $pointsvar until it reaches 20000. It was working until I made it go through each location in a while loop and now it just outputs Inserted 0
I have increased the max_execution_time as it could possible take a looong time to run. This script will be run on a cron around every day or week.
The expected output would be Inserted and a very very very big number..
Thanks for any help you can provide :D

Use for loops instead of while loops to ensure that your variables get initialized properly each time.
$inserts = 0;
for ($locationvar = 32000006; $locationvar <= 32000260; $locationvar++){
for ($pointsvar = 50000; $pointsvar >= 20000; $pointsvar -= 500){
$url = "http://185.112.249.77:9999/Api/Search?search=&level=0&min=1&max=50&points=$pointsvar&loc=$locationvar";
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$in=$data['clanList'];
$results = $data['results']; //max is 64
for ($i = 0; $i < $results; $i++){
$clanid = $in[$i]['id'];
$clanname = mysqli_real_escape_string($con,$in[$i]['name']);
$clanplayerCount = $in[$i]['playerCount'];
$clanwarswon = $in[$i]['warsWon'];
$clanwarslost = $in[$i]['warsLost'];
$clanwarstied = $in[$i]['warsTied'];
$clanLocation = mysqli_real_escape_string($con,$in[$i]['clanLocation']);
$clanlevel = $in[$i]['level'];
$score = $in[$i]['score'];
$sql = "INSERT INTO activeclans(id, name, location, playercount, clanlevel, warswon, warslost, warstied, score)
VALUES('$clanid', '$clanname', '$clanLocation', '$clanplayerCount', '$clanlevel', '$clanwarswon', '$clanwarslost', '$clanwarstied', $score)";
mysqli_query($con, $sql);
$inserts++;
}
sleep(1);
}
sleep(1);
}
echo "Inserted $inserts";
Also, maybe the innermost loop should be foreach ($data['clanList'] as $clan) -- can the number of clans in the clanList array be different from $data['results']?
And you can speed up INSERT queries by inserting multiple rows with a single query:
INSERT INTO tablename (columns...) VALUES (...), (...), (...), ...
So in your script, you could concatenate all the values during the loop over clans, and then insert that batch at the end of that loop. So it would look like:
$values = array();
for ($i = 0; $i < $results; $i++){
$clanid = $in[$i]['id'];
$clanname = mysqli_real_escape_string($con,$in[$i]['name']);
$clanplayerCount = $in[$i]['playerCount'];
$clanwarswon = $in[$i]['warsWon'];
$clanwarslost = $in[$i]['warsLost'];
$clanwarstied = $in[$i]['warsTied'];
$clanLocation = mysqli_real_escape_string($con,$in[$i]['clanLocation']);
$clanlevel = $in[$i]['level'];
$score = $in[$i]['score'];
$values[] = "('$clanid', '$clanname', '$clanLocation', '$clanplayerCount', '$clanlevel', '$clanwarswon', '$clanwarslost', '$clanwarstied', $score)";
}
$sql = "INSERT INTO activeclans(id, name, location, playercount, clanlevel, warswon, warslost, warstied, score)
VALUES " . implode(', ', $values);
mysqli_query($con, $sql);
$inserts += count($values);

You are not resetting $pointsvar = 50000; when the second loop is completed. I would expect that the second loop would therefore only run on the first time round the outer loop. So
<?php
ini_set('max_execution_time', 0);
include("../includes/mysqli.php");
$pointsvar = 50000;
$inserts = 0;
$locationvar = 32000006;
while($locationvar <= 32000260){
while($pointsvar >= 20000){
$url = "http://185.112.249.77:9999/Api/Search?search=&level=0&min=1&max=50&points=$pointsvar&loc=$locationvar";
$jsondata = file_get_contents($url);
$data = json_decode($jsondata, true);
$in=$data['clanList'];
$results = $data['results']; //max is 64
$i = 0;
while($i + 1 <= $results){
$clanid = $in[$i]['id'];
$clanname = mysqli_real_escape_string($con,$in[$i]['name']);
$clanplayerCount = $in[$i]['playerCount'];
$clanwarswon = $in[$i]['warsWon'];
$clanwarslost = $in[$i]['warsLost'];
$clanwarstied = $in[$i]['warsTied'];
$clanLocation = mysqli_real_escape_string($con,$in[$i]['clanLocation']);
$clanlevel = $in[$i]['level'];
$score = $in[$i]['score'];
$sql = "INSERT INTO activeclans(id, name, location, playercount, clanlevel, warswon, warslost, warstied, score)
VALUES('$clanid', '$clanname', '$clanLocation', '$clanplayerCount', '$clanlevel', '$clanwarswon', '$clanwarslost', '$clanwarstied', $score)";
mysqli_query($con, $sql);
$i++;
$inserts++;
}
$pointsvar = $pointsvar-500;
sleep(1);
}
$locationvar++;
// RESET The pointsvar counter
$pointsvar = 50000;
sleep(1);
}
echo "Inserted $inserts";
?>

Related

When i run this code the counter only goes 1 and 2 but i want to make it go 5

When i run this php code the counter variable only goes 1 and 2 but i want to make it go 5 what is wrong here anyone can help me ? why the counter dosent go up from 2 ?
<?php
session_start();
include "sql.php";
$date = $_POST['date'];
$email = $_SESSION[email];
$counter = 0;
$check = " select * from reservations where date = '$date'";
$result = mysqli_query($con, $check);
$num = mysqli_num_rows($result);
if($num = 1){
$data = " select * from reservations where date = '$date'";
$dresult = mysqli_query($con, $data);
$row = mysqli_fetch_array($dresult);
$counter = $row[counter];
echo $counter;
if ($counter < 5){
$counter=$counter+1;
$reg= "insert into reservations(date,counter,email) values('$date' , '$counter' , '$email')";
mysqli_query($con, $reg);
}
else{
echo "no tables available";
}
}
else{
$data = " select * from reservations where date = '$date'";
$dresult = mysqli_query($con, $data);
$row = mysqli_fetch_array($dresult);
$counter = $row[counter];
$counter=$counter+1;
$reg= "insert into reservations(date,counter,email) values('$date' , '$counter' , '$email')";
mysqli_query($con, $reg);
}
I think you should put it on a looping.
Check code below:
<?php
session_start();
include "sql.php";
$date = $_POST['date'];
$email = $_SESSION[email];
$counter = 0;
$check = " select * from reservations where date = '$date'";
$result = mysqli_query($con, $check);
$num = mysqli_num_rows($result);
if($num = 1){
$data = " select * from reservations where date = '$date'";
$dresult = mysqli_query($con, $data);
$row = mysqli_fetch_array($dresult);
$counter = $row[counter];
echo $counter;
if ($counter < 5){
while($counter <= 5){
//$counter=$counter+1;
$reg= "insert into reservations(date,counter,email) values('$date' , '$counter' , '$email')";
mysqli_query($con, $reg);
$counter++;
}
}
else{
echo "no tables available";
}
}
else{
$data = " select * from reservations where date = '$date'";
$dresult = mysqli_query($con, $data);
$row = mysqli_fetch_array($dresult);
$counter = $row[counter];
$counter=$counter+1;
$reg= "insert into reservations(date,counter,email) values('$date' , '$counter' , '$email')";
mysqli_query($con, $reg);
}

How to save two transaction in my shopping cart

i have two transaction on my cart.
while i click checkout, why $grand total only one inserted to my db.
and when i echo $grand, it appear two total.
this is my function
function cart(){
$username = $_SESSION['UserID'];
$cart = array();
$sql = mysql_query("SELECT * FROM cart WHERE Username='$username'");
while ($r=mysql_fetch_array($sql)) {
$cart[] = $r;
}
return $cart;
}
this is my process code
for ($i = 0; $i < $j; $i++){
echo $start= $cart[$i]['City_Saler'];
echo $end= $cart[$i]['City_Cust'];
$price= $cart[$i]['Price'];
$gram= $cart[$i]['gram'] / 1000;
echo $kg= ceil($gram);
$query= mysql_query("select * FROM service WHERE Start_Destination='$start' AND End_Destination='$end'");
while($query_row = mysql_fetch_assoc($query)){
$grand=$query_row['ServPriceKG'] + $price ;
}
}
for ($i = 0; $i < $j; $i++){
mysql_query("INSERT INTO ordering_detail(ID_Transaction, ID_Product, User_ID, Service_Name, Service_Package, Qty, gram, Price, Receiver_Name, Receiver_City, Receiver_Subdis, Receiver_Address, Receiver_Prov, Receiver_Phone, Grandtotal, Payment, Stat_Transfer_Item, ID_Saler)
VALUES('$idtransaction', '{$cart[$i]['ID_Product']}', '$cusid', '$service', '$paket', '{$cart[$i]['qty']}', '$kg', '{$cart[$i]['Price']}', '$name', '$reci', '$subdis', '$address', '$prov', '$phone', '$grand', '-', '-', '{$cart[$i]['ID_Saler']}')");
}
mysql_query("DELETE FROM preview_ordering WHERE ID_Preview= '$id'");
for ($i = 0; $i < $j; $i++) { mysql_query("DELETE FROM cart WHERE ID = {$cart[$i]['ID']}");}
header('Location:cart.php');
please help me out

Php query for loop does not work as expected

I have the following php script that query a mysql database in order to send a message. I want to send the "message" variable in loops every 1000 rows of the database table. Below is the code, what is wrong with this?
<?php
$num = $con->query("SELECT gcm_regid from gcm_users")->rowCount();
$current_num = 0;
$message = $_POST["message"];
for ($i = 0; $i < $num / 999; $i++) {
$query = $con->query("SELECT gcm_regid from gcm_users LIMIT $current_num, 999");
foreach ($query as $data) {
$row[] = $data["gcm_regid"];
}
$pushStatus = send_notification($con, $row, $message);
$current_num += 999;
}
?>
https://jsfiddle.net/yLff8n5d/
check this
<?php
$num = $con->query("SELECT gcm_regid from gcm_users")->rowCount();
$current_num = 0;
$message = $_POST["message"];
for ($i = 0; $i < $num / 999; $i++) {
$query = $con->query("SELECT gcm_regid from gcm_users LIMIT $current_num, 999");
$row = array()
while($result = $query->fetch_assoc()){
$row[] = $result['gcm_regid']
}
$pushStatus = send_notification($con, $row, $message);
$current_num += 999;
}
?>

Premature end of script headers: php-cgi and internal server error

need some helps here: i try to import some excel sheets to my website, but the page keep loading and then stop working and showing internal server error text. the error log shows this caused by the import.php :Premature end of script headers: php-cgi, referer: ...file_import.php.
below are the codes:
<? include("../include/begin.inc.php");?>
<?
function showerror()
{
die("Error " . mysql_errno() . " : " . mysql_error());
}
function sava_data($array, $table){
$count = 0;
$total = 0;
foreach( $array as $tmp){
if ($count <> 0){
$date = date("Y:m:d H:i:s");
$sql = "INSERT INTO $table set ";
$sql .= "detail = '{$tmp[2]}', shape = '{$tmp[3]}', qty = '{$tmp[4]}', price = '{$tmp[5]}', percent = '{$tmp[6]}', colour = '{$tmp[7]}', clarity = '{$tmp[8]}', prop = '{$tmp[9]}', polish = '{$tmp[10]}', smy = '{$tmp[11]}', diam = '{$tmp[12]}', t_dep = '{$tmp[13]}', `table` = '{$tmp[14]}', fl = '{$tmp[15]}', colour_shade = '{$tmp[16]}', cert = '{$tmp[17]}', cert_no = '{$tmp[18]}', per_kg = '{$tmp[19]}', selling_price = '{$tmp[20]}', status = 'new', create_date = '{$date}'";
//echo $sql."<br>";
//exit();
if (!($result = #mysql_query($sql) or die("Error:" . mysql_error().$sql)))
showerror();
$total++;
}
$count++;
}
return $total;
}
function save_data2($array,$table){
$count = 0;
$total = 0;
foreach( $array as $tmp){
if ($count <> 0){
$date = date("Y:m:d H:i:s");
$sql = "INSERT INTO $table set ";
$sql .= "detail = '{$tmp[2]}', shape = '{$tmp[3]}', qty = '{$tmp[4]}', price = '{$tmp[5]}', percent = '{$tmp[6]}', colour = '{$tmp[7]}', clarity = '{$tmp[8]}', prop = '{$tmp[9]}', polish = '{$tmp[10]}', smy = '{$tmp[11]}', diam = '{$tmp[12]}', t_dep = '{$tmp[13]}', `table` = '{$tmp[14]}', fl = '{$tmp[15]}', colour_shade = '{$tmp[16]}', cert = '{$tmp[17]}', cert_no = '{$tmp[18]}', per_kg = '{$tmp[19]}', selling_price = '{$tmp[20]}', status = 'new', create_date = '{$date}'";
//echo $sql."<br>";
//exit();
if (!($result = #mysql_query($sql) or die("Error:" . mysql_error().$sql)))
showerror();
$total++;
}
$count++;
}
return $total;
}
function empty_data($table){
if($table == "fancy_table"){
$s3 = "select * from $table where file != ''";
$r3 = mysql_query($s3);
while($d3 = mysql_fetch_array($r3)){
$del_lo_l="../../_files/fancy_product/".$d3['file'];
if(file_exists($del_lo_l))
{
#unlink($del_lo_l);
}
}
}
$s4 = "truncate table `$table`";
mysql_query($s4);
$s5 = "OPTIMIZE TABLE `$table`";
mysql_query($s5);
}
//error_reporting(E_ALL ^​​ E_NOTICE);
$action = $_REQUEST['action'];
if($_POST){
if($action == "empty"){
empty_data("artwork");
}else if($action == "imported"){
$Import_TmpFile = $_FILES['file']['tmp_name'];
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('UTF-8');
$data->read($Import_TmpFile);
$total = 0;
//for ($i = 4; $i <= $data->sheets[0]['numRows']; $i++) {
for ($i = 4; $i <= 65536; $i++) {
if ($data->sheets[0]['cells'][$i][2] <> ""){
$sql = "INSERT INTO artwork set detail = '".$data->sheets[0]['cells'][$i][2]."', shape = '".$data->sheets[0]['cells'][$i][3]."', qty = '".$data->sheets[0]['cells'][$i][4]."', price = '".$data->sheets[0]['cells'][$i][5]."', percent = '".$data->sheets[0]['cells'][$i][6]."', colour = '".$data->sheets[0]['cells'][$i][7]."', clarity = '".$data->sheets[0]['cells'][$i][8]."', prop = '".$data->sheets[0]['cells'][$i][9]."', polish = '".$data->sheets[0]['cells'][$i][10]."', smy = '".$data->sheets[0]['cells'][$i][11]."', diam = '".$data->sheets[0]['cells'][$i][12]."', t_dep = '".$data->sheets[0]['cells'][$i][13]."', `table` = '".$data->sheets[0]['cells'][$i][14]."', fl = '".$data->sheets[0]['cells'][$i][15]."', colour_shade = '".$data->sheets[0]['cells'][$i][16]."', cert = '".$data->sheets[0]['cells'][$i][17]."', cert_no = '".$data->sheets[0]['cells'][$i][18]."', per_kg = '".$data->sheets[0]['cells'][$i][19]."', selling_price = '".$data->sheets[0]['cells'][$i][20]."', status = 'new', create_date = now()";
$result = #mysql_query($sql);
$total++;
}
}
echo $total;
//$total = sava_data($array, "artwork");
}else if($action == "fancy_imported"){
$Import_TmpFile = $_FILES['file']['tmp_name'];
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('UTF-8');
$data->read($Import_TmpFile);
$total = 0;
//for ($i = 4; $i <= $data->sheets[0]['numRows']; $i++) {
for ($i = 4; $i <= 65536; $i++) {
if ($data->sheets[0]['cells'][$i][2] <> ""){
$sql = "INSERT INTO fancy_style set detail = '".$data->sheets[0]['cells'][$i][2]."', artworktype = '".$data->sheets[0]['cells'][$i][3]."', shape = '".$data->sheets[0]['cells'][$i][4]."', qty = '".$data->sheets[0]['cells'][$i][5]."', colour = '".$data->sheets[0]['cells'][$i][6]."', cut = '".$data->sheets[0]['cells'][$i][7]."', measurements = '".$data->sheets[0]['cells'][$i][8]."', treatment = '".$data->sheets[0]['cells'][$i][9]."', origin = '".$data->sheets[0]['cells'][$i][10]."', comments = '".$data->sheets[0]['cells'][$i][11]."', cert = '".$data->sheets[0]['cells'][$i][12]."', cert_no = '".$data->sheets[0]['cells'][$i][13]."', `per_kg` = '".$data->sheets[0]['cells'][$i][14]."', status = 'new', create_date = now()";
$result = #mysql_query($sql);
$total++;
}
}
echo $total;
}else if($action == "fancy_empty"){
empty_data("fancy_style");
}
}
//exit();
jsRedirect(geturlname().".php?action=".$action."&rows=".$total);
?>
<? include("../include/end.inc.php");?>

Update statement in MYSQL from PHP

I have a table as shown below
The output from said table
Green, is where a winner has been announced, whereas yellow means they have submitted a report, but a winner hasn't been decided yet. (winner field not populated)
$roundBound = Array();
$query = "SELECT MIN(id), MAX(id) FROM $tablename GROUP BY round";
if($result = $Login->mysqli->query($query)) {
while ($row = $result->fetch_row()) {
$roundBound[] = $row[0];
$roundBound[] = $row[1];
}
}
for($i = 0; $i < count($roundBound); $i = $i + 2) {
$match = 0;
for($j = $roundBound[$i]; $j < $roundBound[$i + 1]; $j = $j + 2) {
$id1 = $j;
$id2 = $j+1;
$query = "SELECT t1.winner, t2.winner FROM $tablename as t1, $tablename as t2 WHERE t1.id=$id1 AND t2.id=$id2";
$result = $Login->mysqli->query($query);
$row = $result->fetch_row();
$win1 = $row[0];
$win2 = $row[1];
if (isset($win1) && isset($win2)) {
if (isset($roundBound[$i + 2])) {
$id = $roundBound[$i + 2] + $match;
$query = "UPDATE $tablename SET
username = '$win1',
username2 = '$win2'
WHERE id = $id";
$Login->mysqli->query($query);
} else {
//Tourneydonneee yeeee
}
}
$match++;
}
}
Does anyone have a improvement, or an all-around different idea? This will be running quite often and could be potentially running on large record sets, so optimization would also be welcome.
as far as i understand you problem, i can suggest you to try
for ($i = 0; $i < count($arr); $i = $i + 2) {
$win1 = mysql_query("SELECT winner FROM tableName WHERE id=".(int)$i);
$win2 = mysql_query("SELECT winner FROM tableName WHERE id=".(int)$i+1);
$qry = "INSERT INTO tableName SET
username = $win1,
username2 =$win2,
....";
mysql_query($qry);
}

Categories