PHP/SQL script stops unexpectedly, works in debug - php

I have a fairly long script that ran fine until last night (no changes made, that I know of).
The query that needs to be run is this:
$query = "INSERT INTO results SET
compId = ".$comp_id.",
eventId = ".$eventId.",
eventSession = '".$eventsession."',
driverId = ".$driverid.",
teamId = ".$teamid.",
position = ".$this->data['drivers']['position'][$i].",
raceTime = '".$racetime."',
laps = ".$this->data['drivers']['laps'][$i].",
pitstops = ".$this->data['drivers']['pitstops'][$i].",
engine = ".$engineId.",
tyres = '4',
sector1 = '".$sector1."',
sector2 = '".$sector2."',
sector3 = '".$sector3."',
fastestLap = '".$this->data['drivers']['bestTime'][$i]."',
grid = ".$grid;
// If debug is true then just var_dump but don't execute query
if ($this->debug) {
var_dump($query); echo '<br>';
}
else { // debug is false here, then not debug and run mysql query as usual
mysql_query($query);
}
I ran a debug/var_dump script that shows that all data is read correctly, and shows that the script correctly runs for each record in the dataset:
string(341) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 408, teamId = 142, position = 1, raceTime = '', laps = 9, pitstops = 0, engine = 57, tyres = '4', sector1 = '34.8867', sector2 = '35.8517', sector3 = '35.7191', fastestLap = '106.4575', grid = 0"
string(342) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 1910, teamId = 316, position = 2, raceTime = '', laps = 9, pitstops = 0, engine = 57, tyres = '4', sector1 = '35.0853', sector2 = '35.6669', sector3 = '35.7169', fastestLap = '106.4692', grid = 0"
string(343) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 1934, teamId = 201, position = 3, raceTime = '', laps = 11, pitstops = 0, engine = 51, tyres = '4', sector1 = '35.1301', sector2 = '35.7618', sector3 = '35.7473', fastestLap = '106.6393', grid = 0"
string(343) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 1263, teamId = 286, position = 4, raceTime = '', laps = 10, pitstops = 0, engine = 53, tyres = '4', sector1 = '35.0674', sector2 = '35.7036', sector3 = '35.9128', fastestLap = '106.6838', grid = 0"
string(342) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 1255, teamId = 286, position = 5, raceTime = '', laps = 8, pitstops = 3, engine = 53, tyres = '4', sector1 = '35.1663', sector2 = '35.9540', sector3 = '35.6342', fastestLap = '106.7544', grid = 0"
string(340) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 1190, teamId = 8, position = 6, raceTime = '', laps = 3, pitstops = 0, engine = 51, tyres = '4', sector1 = '35.1284', sector2 = '35.8531', sector3 = '35.8777', fastestLap = '106.8593', grid = 0"
string(342) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 1092, teamId = 253, position = 7, raceTime = '', laps = 8, pitstops = 1, engine = 55, tyres = '4', sector1 = '35.2606', sector2 = '35.9344', sector3 = '35.7010', fastestLap = '106.8960', grid = 0"
string(342) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 1393, teamId = 154, position = 8, raceTime = '', laps = 9, pitstops = 0, engine = 58, tyres = '4', sector1 = '35.1497', sector2 = '35.8700', sector3 = '36.0847', fastestLap = '107.1044', grid = 0"
string(342) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 2048, teamId = 251, position = 9, raceTime = '', laps = 9, pitstops = 1, engine = 55, tyres = '4', sector1 = '35.2091', sector2 = '36.1934', sector3 = '35.8702', fastestLap = '107.2728', grid = 0"
string(343) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 621, teamId = 308, position = 10, raceTime = '', laps = 12, pitstops = 0, engine = 51, tyres = '4', sector1 = '35.2224', sector2 = '36.0565', sector3 = '36.3339', fastestLap = '107.6127', grid = 0"
string(342) "INSERT INTO results SET compId = 8, eventId = 934, eventSession = 'P', driverId = 447, teamId = 232, position = 11, raceTime = '', laps = 9, pitstops = 0, engine = 57, tyres = '4', sector1 = '35.1237', sector2 = '36.2297', sector3 = '36.2870', fastestLap = '107.6404', grid = 0"
However, when not in debug, this only runs for the first record in the set. No matter what dataset I feed into.
I am at a loss at explaining what is going wrong or if there is anything that stops the script after the first instance (which is entered correctly).
Note: the original code is not mine and I no longer have access to the original developer as he left our group, so I am just basing myself of the current information. As mentioned earlier, this script has worked correctly until last night and no changes have been made to other parts of the code that may affect it.
Thank you for any help!
EDIT: here is the whole loop, as requested in the comments:
private function queryDb()
{
$year=gmdate("Y");
// What $this->data holds at this point is an array with all drivers, positions, times, etc
// using ['driver'][0] => Jim Parisis that correspond to ['position'][0] => 1 and the ['bestTime'][0] => 95.9577 and so on
// Let's pick the event Id from $this->data
$eventId = $this->data['event'];
$eventsession = $this->data['evsess'];
// instantiate the finances class
// So we can use later any of its method like $finances->makeSomething($argument)
$finances = new Finances($eventId, $this->debug);
// Let's get the competition holding that event
$query = "SELECT competition FROM ".$this->dbName.".calendar WHERE id='$eventId'";
$result = mysql_query($query);
// $comp_id = mysql_fetch_row($result); // What you have there is an array array(1) { [0]=> string(1) "1" }
// That's true that competition is 1 but having in array you have to access it like $comp_id[0]
while ($row = mysql_fetch_row($result))
$comp_id = (int)$row[0]; // Better build it as simple integer to save memory
mysql_free_result($result);
// echo '<pre>'; print_r($this->data); echo '</pre>';
$i = 0; // Let's build some integer to play with because we have keys starting at 0 in the $this->data array
foreach ($this->data['drivers']['name'] as $key => $value) {
$driverFullName = $value; // now the foreach goes for each element of the 'drivers' key storing it in the $value variable
// Gets the users id
$query = "SELECT id FROM ".$this->dbName.".users WHERE CONCAT(firstName,' ',lastName) ='".$driverFullName."'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result))
$driverid = $row[0];
mysql_free_result($result);
//var_dump($driverid);
// Gets the partA from contracts
$teamid = NULL;
if ($comp_id==10) { $teamid= 0; }
else {
$query = "SELECT partA FROM ".$this->dbName.".contracts WHERE partB ='".$driverid."' AND competition ='".$comp_id."' AND curState ='A'";
$result = mysql_query($query);
if (mysql_num_rows($result) != 0) {
while ($row = mysql_fetch_row($result))
$teamid = $row[0];
}
else { $teamid=0; echo "Warning: driver $driverFullName has no contract."; }
mysql_free_result($result);
}
//var_dump($teamid);
// Gets the engine
// We can wrap this and the next queries in just one by using LEFT JOIN but that's another story
$enginemodel = NULL;
$engineId = NULL;
/*$query = "SELECT te.engine as engineId, e.engine as engineModel, en.id as engineId2 FROM DCO_team_engines te LEFT JOIN DCO_engines e ON te.engine=e.id LEFT JOIN engines en ON en.brand=e.engine WHERE te.team ='".$teamid."' AND te.comp='".$comp_id."' AND te.year ='".$year."'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result))
$engineid = $row[2];
mysql_free_result($result);*/
//Substitute engine
$query = "SELECT engine FROM ".$this->dbName.".DCO_team_engines WHERE team ='".$teamid."' AND comp ='".$comp_id."' AND year ='".$year."'";
$result = mysql_query($query);
if (mysql_num_rows($result) != 0) {
while ($row = mysql_fetch_row($result))
$engineId = $row[0];
}
mysql_free_result($result);
$query = "SELECT vehchoice FROM ".$this->dbName.".competitions WHERE id ='".$comp_id."'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result))
$vehchoice = $row[0];
mysql_free_result($result);
if ($vehchoice==1) {
$query = "SELECT classes FROM ".$this->dbName.".licenses WHERE competition ='".$comp_id."' AND applicantId ='".$teamid."' AND concept ='2' AND validDate='".$year."'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result))
$engineId = $row[0];
mysql_free_result($result);
}
//var_dump($engineId); echo '<br>';
// $this->data['sectors']['s1'][] = $sector1;
// $this->data['sectors']['s2'][] = $sector2;
// $this->data['sectors']['s3'][] = $sector3;
$sector1 = $this->data['sectors']['s1'][$i];
$sector2 = $this->data['sectors']['s2'][$i];
$sector3 = $this->data['sectors']['s3'][$i];
$laps = $this->data['drivers']['laps'][$i];
$position = $this->data['drivers']['position'][$i];
$finishstatus = $this->data['drivers']['finishStatus'][$i];
$untimed = $this->data['drivers']['untimed'][$i];
$carnumber = $this->data['drivers']['carnumber'][$i];
if ($finishstatus=='Finished Normally') { $racetime = $this->data['drivers']['finishTime'][$i]; }
if ($finishstatus=='DNF') { $racetime = "DNF"; }
$grid = 0; // grid is always empty until the following condition applies
if ($eventsession=='R' || $eventsession=='R1' || $eventsession=='R2' || $eventsession=='R3') {
$laprank = $this->data['drivers']['fastestlaprank'][$i];
$grid = $this->data['drivers']['gridpos'][$i];
}
if ($engineId == null)
$engineId = 'DEFAULT';
if ($comp_id=='12') { $carchosen = $this->data['drivers']['team'][$i];
$query = "SELECT id FROM ".$this->dbName.".available_vehicles WHERE label ='".$carchosen."'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result))
$engineId = $row[0];
mysql_free_result($result);
}
$query = "INSERT INTO results SET
compId = ".$comp_id.",
eventId = ".$eventId.",
eventSession = '".$eventsession."',
driverId = ".$driverid.",
teamId = ".$teamid.",
position = ".$this->data['drivers']['position'][$i].",
raceTime = '".$racetime."',
laps = ".$this->data['drivers']['laps'][$i].",
pitstops = ".$this->data['drivers']['pitstops'][$i].",
engine = ".$engineId.",
tyres = '4',
sector1 = '".$sector1."',
sector2 = '".$sector2."',
sector3 = '".$sector3."',
fastestLap = '".$this->data['drivers']['bestTime'][$i]."',
grid = ".$grid;
// If debug is true then just var_dump but don't execute query
if ($this->debug) {
var_dump($query); echo '<br>';
}
else { // debug is false here, then not debug and run mysql query as usual
mysql_query($query);
}
// Ok, if you need to call fines method within the loop
// call it here, for example to insert rows depending on the driver values like laps, pitstops, etc.
// Notice we parse the whole array
$query = "SELECT careerLadder, usesManagement, vehchoice, monoEngine FROM ".$this->dbName.".competitions WHERE id='$comp_id'";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
$careerLadder = (int)$row[0]; // Better build it as simple integer to save memory
$usesManagement = (int)$row[1];
$vehchoice = (int)$row[2];
$monoEngine = (int)$row[3];
}
mysql_free_result($result);
if ($comp_id!=10)
{
if (($eventsession!='T')&&($eventsession!='P')&&($eventsession!='Q'))
{
$finances->standings($comp_id,$position, $driverid, $year, $teamid, $eventsession, $laps);
$finances->standingsarrange($comp_id);
}
}
if ($usesManagement==1)
{
$finances->ladderfinances($teamid, $comp_id, $eventsession, $position, $laprank,$laps);
}
if ($comp_id==1)
{
if ($eventsession=='T')
{
$finances->rdpoints($teamid,$comp_id,$laps,$untimed);
$finances->erdpoints($teamid,$comp_id,$laps,$untimed);
}
if (($eventsession!='T')&&($eventsession!='P'))
{
$finances->enginewear($driverid,$teamid,$laps,$carnumber);
}
}
$i++; // ok let's go to the next element if any, if foreach notices it's the last then it stops :)
}
$finances->standingstiebreak($comp_id);
//if ($dom->getElementsByTagName('Qualify')->item(0))
// $this->data['session'] = $dom->getElementsByTagName('Qualify')->item(0)->nodeName;
//if ($dom->getElementsByTagName('Practice1')->item(0))
// $this->data['session'] = $dom->getElementsByTagName('P')->item(0)->nodeName;
if ($eventsession=='T') { $session = "Test"; }
if ($eventsession=='P') { $session = "Practice"; }
if ($eventsession=='Q') { $session = "Qualifying"; }
if ($eventsession=="R") { $session = "Race"; }
if ($eventsession=='R1') { $session = "Race 1"; }
if ($eventsession=='R2') { $session = "Race 2"; }
if ($eventsession=='R3') { $session = "Race 3"; }
echo "<h2>$session results entered successfully</h2>";

Issue resolved - the DB in which we were trying to add the rows had the ID field set to smallint. We had literally reached the limit of rows (65535) and therefore it was working on debug and not in real life.

Related

error when I add break to foreach loop

Okay, this is really frustrating me and I don't know why. I have been scouring the internet for at least two days trying to figure out the problem. I am trying to pull xp amount for a certain skill for all the names stored in the database. It echoed the specified xp for all the users in the database, but was repeating the values with an undefined index. Even though that error is there it still prints the values. I researched the internet and found that break will stop the repeating, but when I add the break it then wont print the values and just gives me the undefined index. THe index does exist.
$sql = "SELECT rsn FROM users";
$qry = $conn->prepare($sql);
$qry->execute();
while($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$rsn = $row['rsn'];
$hs = file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=". $rsn);
$hs = explode("\n",$hs);
$skills = array("Overall","Attack","Defence","Strength","Constitution","Ranged","Prayer","Magic","Cooking","Woodcutting","Fletching","Fishing","Firemaking","Crafting","Smithing","Mining","Herblore","Agility","Thieving","Slayer","Farming","Runecrafting","Hunter","Construction","Summoning","Dungeoneering", "Divination", "Invention");
$i = 0;
foreach(array_unique($skills) as $value){
$hs[$i] = explode(",",$hs[$i]);
$stats[$value]["rank"] = number_format($hs[$i][0]);
$stats[$value]["level"] = number_format($hs[$i][1]);
$stats[$value]["xp"] = number_format($hs[$i][2]);
$i++;
/*require_once 'tourny_config_include.php';
$sql = "UPDATE active_tourny SET xp = :xp AND from_date = :from AND to_date = :to WHERE rsn = :rsn";
$qry = $conn->prepare($sql);
$qry->execute(array(':xp' => $xp, ':rsn' => $rsn, ':to' => $tournyTo, ':from' => $tournyFrom));*/
echo $stats["Attack"]["xp"] . '<br>';
break;
}
}
$qry = $conn->prepare($sql);
$qry->execute();
while($row = $qry->fetch(PDO::FETCH_ASSOC)) {
$rsn = $row['rsn'];
$hs = file_get_contents("http://hiscore.runescape.com/index_lite.ws?player=". $rsn);
$hs = explode("\n",$hs);
$skills = array("Overall","Attack","Defence","Strength","Constitution","Ranged","Prayer","Magic","Cooking","Woodcutting","Fletching","Fishing","Firemaking","Crafting","Smithing","Mining","Herblore","Agility","Thieving","Slayer","Farming","Runecrafting","Hunter","Construction","Summoning","Dungeoneering", "Divination", "Invention");
$i = 0;
foreach($skills as $skill){
$hs[$i] = explode(",",$hs[$i]);
$stats[$skill]["rank"] = number_format($hs[$i][0]);
$stats[$skill]["level"] = number_format($hs[$i][1]);
$stats[$skill]["xp"] = number_format($hs[$i][2]);
$i++;
/*require_once 'tourny_config_include.php';
$sql = "UPDATE active_tourny SET xp = :xp AND from_date = :from AND to_date = :to WHERE rsn = :rsn";
$qry = $conn->prepare($sql);
$qry->execute(array(':xp' => $xp, ':rsn' => $rsn, ':to' => $tournyTo, ':from' => $tournyFrom));*/
// display Attack xp if available
if isset($stats["Attack"]["xp"])
echo $stats["Attack"]["xp"] . '<br>';
}
}
Wow I cannot believe that it was this simple. All I had to do is move
echo $stats["Attack"]["xp"] . '<br>';
outside the foreach loop

Index causes and Error in Updating Row

Why does Index causes an error in MySQL Update row? Removing it makes the Query work.
The error is
MySQLi failed to query: UPDATE quests SET id = '1', FactionID = '2', ReqReputation = '2', ReqClassID = '3', ReqClassPoints = '2', Name = '2', Description = '2', EndText = '2', Experience = '2', GExperience = '2', Copper = '2', Silver = '2', Gold = '2', Coins = '2', Reputation = '2', ClassPoints = '2', RewardType = 'S', Level = '2', Upgrade = '1', Once = '1', Slot = '2', Value = '2', Field = '2', Index = '2', Badges = '3', Guild = '1', GiveMembership = '0', War = '1' WHERE id = 1 - December 20, 2016, 1:58 am
$id = $_POST["Id"];
$FactionID = $_POST["Faction"];
$ReqReputation = $_POST["RequiredReputation"];
$ReqClassID = $_POST["Class"];
$ReqClassPoints = $_POST["ReqClassRank"];
$Name = $_POST["Name"];
$Description = $_POST["Description"];
$EndText = $_POST["EndText"];
$Experience = $_POST["Experience"];
$GExperience = $_POST["GuildExperience"];
$Copper = $_POST["Copper"];
$Silver = $_POST["Silver"];
$Gold = $_POST["Gold"];
$Coins = $_POST["Diamond"];
$Reputation = $_POST["Reputation"];
$ClassPoints = $_POST["ClassPoints"];
$RewardType = $_POST["RewardType"];
$Level = $_POST["Level"];
$Upgrade = $_POST["Upgrade"];
$Once = $_POST["Once"];
$Slot = $_POST["Slot"];
$Value = $_POST["Value"];
$Field = $_POST["Field"];
$QIndex = $_POST["Index"];
$Badges = $_POST["Badges"];
$Guild = $_POST["Guild"];
$GiveMembership = $_POST["GiveMembership"];
$War = $_POST["War"];
$MYSQL_QUERY = $content->DBase('Query', array( 0 => "UPDATE quests SET id = '$id', FactionID = '$FactionID', ReqReputation = '$ReqReputation', ReqClassID = '$ReqClassID', ReqClassPoints = '$ReqClassPoints', Name = '$Name', Description = '$Description', EndText = '$EndText', Experience = '$Experience', GExperience = '$GExperience', Copper = '$Copper', Silver = '$Silver', Gold = '$Gold', Coins = '$Coins', Reputation = '$Reputation', ClassPoints = '$ClassPoints', RewardType = '$RewardType', Level = '$Level', Upgrade = '$Upgrade', Once = '$Once', Slot = '$Slot', Value = '$Value', Field = '$Field', Index = '$Index', Badges = '$Badges', Guild = '$Guild', GiveMembership = '$GiveMembership', War = '$War' WHERE id = $id"));
Function DBase
/** MYSQL IMPROVED EXTENSION (PARENT CLASS) **/
public function DBase($type, $params = array()) {
if (!$this->SITE->CMS->Connection)
SystemExit('No available MySQLi connection', __LINE__, __FILE__);
switch (strtoupper($type)) {
case 'QUERY':
if ($Query = parent::query($params[0])) {
$this->SITE->CMS->TotalQuery++;
return $Query;
} else
SystemExit('MySQLi failed to query: ' . $params[0], __LINE__, __FILE__);
break;
case 'PREPARE':
if ($Query = parent::prepare($params[0])) {
$this->SITE->CMS->TotalQuery++;
return $Query;
} else
SystemExit('MySQLi failed to prepare: ' . $params[0], __LINE__, __FILE__);
break;
case 'ESCAPESTRING':
if ($Escape = parent::real_escape_string($params[0]))
return $Escape;
else
SystemExit('MySQLi failed to escape: ' . $params[0], __LINE__, __FILE__);
break;
}
}
Here is the Table Quest
You're using the wrong variable for index. You define it above as $QIndex but then refer to it as $Index on the last line. Try the following:
$id = $_POST["Id"];
$FactionID = $_POST["Faction"];
$ReqReputation = $_POST["RequiredReputation"];
$ReqClassID = $_POST["Class"];
$ReqClassPoints = $_POST["ReqClassRank"];
$Name = $_POST["Name"];
$Description = $_POST["Description"];
$EndText = $_POST["EndText"];
$Experience = $_POST["Experience"];
$GExperience = $_POST["GuildExperience"];
$Copper = $_POST["Copper"];
$Silver = $_POST["Silver"];
$Gold = $_POST["Gold"];
$Coins = $_POST["Diamond"];
$Reputation = $_POST["Reputation"];
$ClassPoints = $_POST["ClassPoints"];
$RewardType = $_POST["RewardType"];
$Level = $_POST["Level"];
$Upgrade = $_POST["Upgrade"];
$Once = $_POST["Once"];
$Slot = $_POST["Slot"];
$Value = $_POST["Value"];
$Field = $_POST["Field"];
$QIndex = $_POST["Index"];
$Badges = $_POST["Badges"];
$Guild = $_POST["Guild"];
$GiveMembership = $_POST["GiveMembership"];
$War = $_POST["War"];
$MYSQL_QUERY = $content->DBase('Query', array( 0 => "UPDATE quests SET id = '$id', FactionID = '$FactionID', ReqReputation = '$ReqReputation', ReqClassID = '$ReqClassID', ReqClassPoints = '$ReqClassPoints', Name = '$Name', Description = '$Description', EndText = '$EndText', Experience = '$Experience', GExperience = '$GExperience', Copper = '$Copper', Silver = '$Silver', Gold = '$Gold', Coins = '$Coins', Reputation = '$Reputation', ClassPoints = '$ClassPoints', RewardType = '$RewardType', Level = '$Level', Upgrade = '$Upgrade', Once = '$Once', Slot = '$Slot', Value = '$Value', Field = '$Field', Index = '$QIndex', Badges = '$Badges', Guild = '$Guild', GiveMembership = '$GiveMembership', War = '$War' WHERE id = $id"));
Also see #Rahul 's comment too. Your: "WHERE id='$id'" seems to be passing the wrong value. An ID is most likely not that version of a date/time. if you want to use the current date + time you could us something like NOW() It gives you the current date and time down to the second.

PHP, using Joomla, algorithm, networking if else,

Hi, I have a question, when i ever insert this code
if ($pointsreach>=$tempunilevel ){
mysql_query("UPDATE `incentives_table` SET pointsreach = pointsreach +500 where userid = '$newsponsorid' ");
the if statement does not work anymore
if (count($items) >0 && $lev <= 10 ){ // found get sponsor id for the next computation
$sponsorid = $items->upline; //sponsor id
but when i remove the
if ($pointsreach>=$tempunilevel ){
mysql_query("UPDATE `incentives_table` SET pointsreach = pointsreach +500 where userid = '$newsponsorid' ");
the statement works perfectly ...
$query = " UPDATE `#__eds_incentives_table` SET `temp` = `temp` + 25 where `userid` = '$sponsorid' ";
$db->setQuery($query);
$db->query();
$mote = $this->entryuni($sponsorid, $lev + 1, +25);
}
else {
return 'ok';
}
This is the code
public function entryuni($newsponsorid = null, $lev = 2, $fpv = 0)
{
$db = & JFactory::getDBO();
$query = "SELECT upline,fslot FROM `table` where userid = '$newsponsorid' ";
$db->setQuery($query);
$items = $db->loadObject();
$items = (!empty($items)) ? $items : array();
$queryreach = mysql_query("SELECT * FROM incentives_table WHERE userid = '$newsponsorid' ");
$fetchreach = mysql_fetch_array($queryreach);
$pointsreach=$fetchreach['pointsreach'];
$tempunilevel=$fetchreach['temp_unilevel'];
if ($pointsreach>=$tempunilevel ){
mysql_query("UPDATE `incentives_table` SET pointsreach = pointsreach +500 where userid = '$newsponsorid' ");
if (count($items) >0 && $lev <= 10 ){ // found get sponsor id for the next computation
$sponsorid = $items->upline; //sponsor id
$query = " UPDATE `#__eds_incentives_table` SET `temp` = `temp` + 25 where `userid` = '$sponsorid' ";
$db->setQuery($query);
$db->query();
$mote = $this->entryuni($sponsorid, $lev + 1, +25);
}
else {
return 'ok';
}

max_execution time limit php

I have a problem that I've been trying to solve for the last couple of days.
I have a site where I crawl news and that works perfectly.
Recently however, I've encountered a problem with my analyzer_script as it appears to exceed the time limit my web host has set. Apparently there is an max_execution time at about 1 minute, and my script takes way longer than that. And I'm not able to adjust that in the php.ini script since I'm hosting my website on a public server.
What can I do? Do I need to rewrite my script?
I appreciate your help!
My script is below:
<?php
$array = array();
$sub_array = array();
$analyzer_ids = array();
$res5 = mysqli_query($con,"SELECT id,status FROM statuz ORDER BY id DESC LIMIT 1");
$row5 = mysqli_fetch_array($res5);
$status = $row5['status'];
$status_id = $row5['id'];
if($status == 2) {
$res1 = mysqli_query($con,"SELECT tag, id FROM tags");
while($row1 = mysqli_fetch_array($res1)) {
$tag = $row1['tag'];
$id = $row1['id'];
$res2 = mysqli_query($con,"SELECT sub_tag FROM sub_tags WHERE tag_id = '$id'");
while($row2 = mysqli_fetch_array($res2)) {
$sub_tag = $row2['sub_tag'];
$sub_tag = strtolower($sub_tag);
$sub_array[] = $sub_tag;
}
$array[] = array('tag_id' => $id, 'tag' => $tag, 'sub_tag' => $sub_array);
$sub_array = array();
}
mysqli_query($con,"INSERT INTO analyzer_queue (crawler_id, status)
(SELECT id,0 FROM crawlers)");
$initial_res = mysqli_query($con,"SELECT crawler_id,id FROM analyzer_queue WHERE status = '0'");
while($initial_row = mysqli_fetch_array($initial_res)) {
$analyzer_id = $initial_row['id'];
$start_crawler_id = $initial_row['crawler_id'];
mysqli_query($con,"UPDATE analyzer_queue SET status = '1' WHERE crawler_id = '$start_crawler_id' ORDER BY id DESC LIMIT 1");
$analyzer_ids[] = $analyzer_id;
$res = mysqli_query($con,"SELECT cr.title, cr.content, cr.id
FROM crawler_results cr
INNER JOIN crawlers c
ON c.newspaper_id = cr.newspaper_id
WHERE c.id = '$start_crawler_id'
AND status = '3'
LIMIT 10");
while($row = mysqli_fetch_array($res)) {
$article_id = $row['id'];
$title = $row['title'];
$content = $row['content'];
$content = strip_tags($content);
$content = strtolower($content);
$title = strtolower($title);
$count = array();
foreach ($array as $tag) {
$regex = '/(?:\b' . preg_quote($tag['tag'], '/');
foreach ($tag['sub_tag'] as $sub) {
$regex .= '\b)|(?:\b' . preg_quote($sub, '/');
}
$regex .= '\b)/i';
$count_content = preg_match_all($regex, $content, $count_content);
$count_title = preg_match_all($regex, $title, $count_title);
$count_total[$tag['tag']] = $count_content + $count_title;
$total_count = $count_total[$tag['tag']];
$tag_name = $tag['tag'];
$res5 = mysqli_query($con,"SELECT id FROM tags WHERE tag = '$tag_name'");
$row5 = mysqli_fetch_array($res5);
$tag_id = $row5['id'];
if($total_count != 0) {
mysqli_query($con,"INSERT INTO article_tags (article_id,tag_id,count_tags) VALUES('$article_id','$tag_id','$total_count')");
}
echo$count_total[$tag['tag']];
echo"<br /><br />";
}
echo"<pre>";
print_r($count_total);
echo"</pre>";
mysqli_query($con,"UPDATE crawler_results SET status = '2', analyzer_id = '$analyzer_id' WHERE id = '$article_id'");
}
mysqli_query($con,"UPDATE analyzer_queue SET status = '2' WHERE crawler_id = '$start_crawler_id' ORDER BY id DESC LIMIT 1");
}
mysqli_query($con,"UPDATE crawler_results SET status = '4' WHERE analyzer_id NOT IN (".implode(',',$analyzer_ids).")");
mysqli_query($con,"UPDATE statuz SET status = '3' WHERE id = '$status_id'");
print_r($analyzer_ids);
} else {
echo"Not ready yet";
}
?>
You can use ini_set at the top of your script like this:
ini_set('max_execution_time' , 300 );
The above call would set max execution time of the script to five minutes. Here's the doc page:
http://php.net/manual/en/function.ini-set.php
If your host allows, you might also consider running this script via cron or some other scheduling daemon. PHP scripts run in the cli context usually have no execution time limit, or a much higher one.
Try this:
ini_set('max_execution_time', 0);
The original Post

Querying 2 tables from the same database NOT working : PHP it has to be EASY but I do not see it

I would appreciate some help here, I am new to PHP.
I have one database with two tables ( products and categories ), as you can imagine I want to query both tables in order to have the whole picture. The problem is that it is not working. Before I used to have this info in the same table and it worked, so I guess it has something to do with querying two tables from the same PHP file.
This is the code:
$query = "SELECT id, stock, nombre, foto, descripcion, celda , precio
FROM productos
WHERE 1 = 1";
$result = mysql_query($query);
$num = mysql_numrows($result);
$i=0;
$data = array();
while ($i < $num) {
$data_id[$i] = mysql_result($result,$i,"id");
$data_stock[$i] = mysql_result($result,$i,"stock");
$data_nombre[$i] = mysql_result($result,$i,"nombre");
$data_foto[$i] = mysql_result($result,$i,"foto");
$data_precio[$i] = mysql_result($result,$i,"precio");
$data_celda[$i] = mysql_result($result,$i,"celda");
$data_descripcion[$i] = mysql_result($result,$i,"descripcion");
++$i;
}
$query2 = "SELECT namec, picturec
FROM categorias
WHERE 1 = 1 ";
$result2 = mysql_query($query2);
$num2 = mysql_numrows($result2);
$h = 0;
while ($h < $num2) {
$data_celda_nombre[$h] = mysql_result($result2,$h,"namec");
$data_celda_foto[$h] = mysql_result($result2,$h,"picturec");
++$h;
}
$data = array(
"ids" => $data_id,
"stocks" => $data_stock,
"nombre" => $data_nombre,
"foto" => $data_foto,
"precio" => $data_precio,
"celda" => $data_celda,
"descripcion" => $data_descripcion,
"celda_foto" => $data_celda_foto,
"celda_nombre" => $data_celda_nombre
);
echo (json_encode($data));
The thing is I am not getting named and picturec , WHY?
Can anyone help me?
Thanks a lot.
Roberto L.
Try this code - I haven't really changed anything, just refactored the code so it is more "standard", if this still doesn't do what you want I will try and work out what problem you are still having.
$data_id = $data_stock = $data_nombre = $data_foto = $data_precio = $data_celda = $data_descripcion = $data_celda_nombre = $data_celda_foto = array();
$query = "SELECT id, stock, nombre, foto, descripcion, celda , precio
FROM productos";
if (!$result = mysql_query($query)) die('MySQL Error: '.mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$data_id[] = $row['id'];
$data_stock[] = $row['stock'];
$data_nombre[] = $row['nombre'];
$data_foto[] = $row['foto'];
$data_precio[] = $row['precio'];
$data_celda[] = $row['celda'];
$data_descripcion[] = $row['descripcion'];
}
$query = "SELECT namec, picturec
FROM categorias";
if (!$result = mysql_query($query)) die('MySQL Error: '.mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$data_celda_nombre[] = $row['namec'];
$data_celda_foto[] = $row['picturec'];
}
$data = array(
"ids" => $data_id,
"stocks" => $data_stock,
"nombre" => $data_nombre,
"foto" => $data_foto,
"precio" => $data_precio,
"celda" => $data_celda,
"descripcion" => $data_descripcion,
"celda_foto" => $data_celda_foto,
"celda_nombre" => $data_celda_nombre
);
echo json_encode($data);

Categories