error when I add break to foreach loop - php

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

Related

How to fetch record to sum upto a value and then add into two new tables?

I am trying to sum (add the values) from the database. My application checks the values from each row, adds up the value from each row up to 2000. And once it reaches up to 2000, it saves in the database (insert query) and continues the same till last record fetched. The total value summed (or totaled) up by each rows should not exceed over 2000.
There are two insert queries, One for inserting the total( from each row between 1800 and 2000) with the ID (like Primary key) generated and the second table add each row inserted with ID (the ID generated becomes now foreign key)
Please refer to the screenshot.
Please find the code below:
$i = 1;
do {
$id = $row_FetchRecordRS['ID'];
$dateissued = $row_FetchRecordRS['DateIssued'];
$rundateCarrierRun = $row_FetchRecordRS['RundateCarrierRunID'];
$timegenerated = $row_FetchRecordRS['TimeGenerated'];
$carrierID = $row_FetchRecordRS['CarrierRunID'] ;
$areaID = $row_FetchRecordRS['CarrierAreaID'];
$address = $row_FetchRecordRS['DeliveryAddress'];
$potzone = $row_FetchRecordRS['Postzone'];
$carr_ID = $row_FetchRecordRS['CarrierID'];
$instruction = $row_FetchRecordRS['DeliveryAddress'];
$areaRep = $row_FetchRecordRS['AreaRepDetails'];
// $vendor = $row_FetchRecordRS['VendorDetails'];
$quantity = $row_FetchRecordRS['Quantity'];
$direct = $row_FetchRecordRS['Direct'];
$jobID = $row_FetchRecordRS['JobID'];
$jobName = $row_FetchRecordRS['JobName'];
$bundlesize = $row_FetchRecordRS['Bundlesize'];
$bundle = $row_FetchRecordRS['Bundles'];
$items = $row_FetchRecordRS['Items'];
$weight = $row_FetchRecordRS['WeightKgs'];
$totalWeightCol = $row_FetchRecordRS['TotalWeightKgs'];
$date = date("D M d, Y G:i");
$total_weight = $row_FetchRecordRS['FinalWeight'] + $total_weight ;
echo "Row: " .$row_FetchRecordRS['FinalWeight']. "<br>";
echo "Total is______ $i : $total_weight <br><br>";
$sqlquerytest = "INSERT INTO `GenerateRun`
(`DateIssued`, `RundateCarrierRunID`, `TimeGenerated`,
`CarrierRunID`, `CarrierAreaID`, `DeliveryAddress`, `Postzone`,
`CarrierID`, `DeliveryInstruction`, `AreaRepDetails`,
`Quantity`, `Direct`, `JobID`, `JobName`, `Bundlesize`,
`Bundles`, `Items`, `WeightKgs`, `TotalWeightKgs`,
`LodingZoneID`)
VALUES
('$dateissued', '$rundateCarrierRun', '$timegenerated',
'$carrierID', '$areaID', '$address', '$potzone', '$carr_ID',
'$instruction', '$areaRep', '$quantity', '$direct', '$jobID',
'$jobName', '$bundlesize', '$bundle', '$items', '$weight',
'$totalWeightCol','$i')";
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
$ResultUpd1 = mysql_query($sqlquerytest, $callmtlc_SalmatDB) or die(mysql_error());
if ($total_weight >= 1800) {
$sqltransitlist = " INSERT INTO `TransitList`(`genID`, `total`) Values ('$i','$total_weight')";
mysql_select_db($database_callmtlc_SalmatDB, $callmtlc_SalmatDB);
$ResultUpd3 = mysql_query($sqltransitlist, $callmtlc_SalmatDB) or die(mysql_error());
$i = $i+1;
$total_weight = 0;
}
} while($row_FetchRecordRS = mysql_fetch_assoc($FetchRecordRS));
Some of your line of codes are irrelevant to your problem. I will simplify it for you.
$i = 1;
$total = 0;
$arr = array(); // for storing a list of data provides that the total doesn't exceed 2000
while ($row = mysql_fetch_assoc($record)) {
$id = $row['id'];
$name = $row['name'];
$num = $row['num'];
$arr[] = array('id' => $id, 'name' => $name, 'num' => $num);
if ($num + $total > 2000) {
$sql = "INSERT INTO Table1(genID, total) Values ('$i','$total')";
mysql_query($sql) or die(mysql_error());
foreach ($arr as $data) {
$sql = "INSERT INTO Table2(ID, name, genID, total) Values ('$data[id]','$data[name]','$i','$data[num]')";
mysql_query($sql) or die(mysql_error());
}
$arr = array(); // empty the array as the data has been stored to database
$i++;
$total = 0;
} else { // if the total doesn't exceed 2000, add it to total
$total += $num;
}
}
$sql = "INSERT INTO Table1(genID, total) Values ('$i','$total')";
mysql_query($sql) or die(mysql_error());
foreach ($arr as $data) {
$sql = "INSERT INTO Table2(ID, name, genID, total) Values ('$data[id]','$data[name]','$i','$data[num]')";
mysql_query($sql) or die(mysql_error());
}
Note: this code is just a sample, not your actual code. You can implement my code and match it to your code.

Unknown column 'E5V7D24M10Y2015' in 'where clause'

I have the code below to update (more 'add to') a row in a database. I have read a few very similar posts, but still can't see where I'm going wrong...
I am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''EventID' = '2' WHERE GameID = 'E2V1D24M10Y2015' AND PlayerID = '55'' at line 1
In this case, 'E5V7D24M10Y2015' is the value of $GameID. I am looking for a column called GameID where the value is E5V7D24M10Y2015, not a column of that name. Please tell me why my $sql is looking for a column named after the value it is looking for.
Each time the function runs the count($Runners) will be different and the values in each variable will be different. That is why I have the SQL in a loop.
if ($formtype == "gameresults"){
$Runners = $_POST['runners'];
$event = $_POST['event'];
$eid = $_POST['eid'];
$vid = $_POST['vid'];
$GameID = $_POST['GameID'];
$date = $_POST['date'];
$season = $_POST['season'];
$region = $_POST['region'];
$notes = $_POST['notes'];
$kev = "kev#email.com";
$email = $_POST['manager'];
$notes = wordwrap($notes,70);
$subject = ("Results for " . $event);
$tix = "";
$cashs = "";
for ($x = 1; $x < ($Runners + 1); $x++){
$ID = $_POST['ID' . $x];
$Name = $_POST['Name' .$x];
$Place = $_POST['Place'.$x];
$Points = $_POST['Points'.$x];
$Cash = $_POST['Cash'.$x];
$Ticket = $_POST['Ticket'.$x];
$vn = $_POST['vn'];
$buyin = $_POST['buyin'];
$data = array($eid,$vid,$region,$buyin,$GameID,$date,$season,$ID,$Name,$Place,$Points,$Ticket,$Cash,$Runners);
$fields = array('EventID','VenueID','Region','Buyin','GameID','Date','Season','PlayerID','Name','Position','Points','Ticket?','Cash','Runners');
for ($x = 0; $x < (count($data) - 1); $x++){
$sql = "UPDATE results SET '$fields[$x]' = '$data[$x]' WHERE GameID = '$GameID' AND PlayerID = '$ID'";
$res = mysqli_query($dbcon, $sql) or die("Update failed. <br>" . mysqli_error($dbcon));
}
You could modify your code to be more clear. I did example but I did not map all the fields so you need to adjust it.
$eid = 4;
$vid = 5;
$region = 'aa';
$buyin = 'asd';
$gameID = 5;
$date = 5;
$playerID = 10;
$fields = array(
'EventID' => $eid,
'VenueID' => $vid,
'Region' => $region,
'Buyin' => $buyin,
'GameID' => $gameID,
'PlayerID'=> $playerID,
'Date' => $date,
);
$numItems = count($fields);
$query = "UPDATE `results` SET ";
$i = 0;
foreach($fields as $name => $value) {
++$i;
if($name == 'GameID' || $name == 'PlayerID') {
continue;
}
$query .= sprintf(" `%s` = '%s'%s ", $name, $value, ($i === $numItems ? "": ","));
}
$query .= sprintf(" WHERE `GameID` = '%d' AND `PlayerID` = '%d'", $fields['GameID'], $fields['PlayerID']);
echo $query;
Fields can be maped via $key => $value and then used in foreach loop. Also using sprintf() makes is more clear to read. However, the best option would be using prepared statements.
Also you don't need to make multiple UPDATE queries, just SET more parameters in one query.
$data = array($eid,$vid,$region,$buyin,$GameID,$date,$season,$ID,$Name,$Place,$Points,$Ticket,$Cash,$Runners);
$fields = array('EventID','VenueID','Region','Buyin','GameID','Date','Season','PlayerID','Name','Position','Points','Ticket?','Cash','Runners');
for ($x = 0; $x < (count($data) - 1); $x++){
$sql = "UPDATE results SET " . $fields[$x] . " = '$data[$x]' WHERE results.GameID = $GameID AND results.PlayerID = $ID";
$res = mysqli_query($dbcon, $sql) or die("Update failed. <br>" . mysqli_error($dbcon));
}
Try this by specifying alias.

PHP MySql PDO Multiple insert doesn't work

I have this code for a multiple insert query (I have to transfer data from db to another and makes some update, so I wanna use a code that could do all this automatically)
$query = "select * from pubblicate order by idPubblicate asc";
$dbh = newPdo2();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query);
$sth->execute();
$count = 0;
$query2 = "insert into published_offer
(codice_onshop,nome,inbreve,anteprima,
galleria1,galleria2,galleria3,galleria4,prezzo,
tp_prezzo,bonus_usabile,proposta,condizioni,
prenotare,categoria,description,keywords,
valido_da,valido_a) ";
while($offerta = $sth->fetch(PDO::FETCH_ASSOC)) {
$array[$count]['id'] = $offerta['idPubblicate'];
$array[$count]['co'] = $offerta['codiceOfferta'];
$array[$count]['no'] = $offerta['nomeOfferta'];
$array[$count]['ib'] = $offerta['inBreve'];
$array[$count]['ke'] = $offerta['keywords'];
$array[$count]['de'] = $offerta['description'];
$array[$count]['pr'] = $pfferta['prezzo'];
$array[$count]['pe'] = $offerta['persona'];
$array[$count]['da'] = $offerta['daTimer'];
$array[$count]['a'] = $offerta['aTimer'];
$array[$count]['an'] = $offerta['anteprima'];
$array[$count]['g1'] = $offerta['galleria1'];
$array[$count]['g2'] = $offerta['galleria2'];
$array[$count]['g3'] = $offerta['galleria3'];
$array[$count]['g4'] = $offerta['galleria4'];
$array[$count]['pro'] = $offerta['proposta'];
$array[$count]['con'] = $offerta['condizioni'];
$array[$count]['pre'] = $offerta['prenotare'];
$array[$count]['bo'] = 999;
if($offerta['italia']=="Sì") $array[$count]['ca'] = "ita";
else if($offerta['europa']=="Sì") $array[$count]['ca'] = "eur";
else if($offerta['mondo']=="Sì") $array[$count]['ca'] = "mon";
$count++;
}
$query2 .= "values (:co,:no,:ib,:an,:g1,:g2,
:g3,:g4,:pr,:pe,:bo,:pro,:con,
:pre,:ca,:de,:ke,:da,:a)";
$dbh = newPdo();
$dbh->exec("set names utf8");
$sth = $dbh->prepare($query2);
$i=0;
echo $array[0]['no'] . " " . count($array) . " " . $array[125]['no'] . "<br>" . $query2 . "<br>";
while($i<count($array)) {
$sth->bindParam(":co", $array[$i]['co']);
$sth->bindParam(":no", $array[$i]['no']);
$sth->bindParam(":ib", $array[$i]['ib']);
$sth->bindParam(":an", $array[$i]['an']);
$sth->bindParam(":g1", $array[$i]['g1']);
$sth->bindParam(":g2", $array[$i]['g2']);
$sth->bindParam(":g3", $array[$i]['g3']);
$sth->bindParam(":g4", $array[$i]['g4']);
$sth->bindParam(":pr", $array[$i]['pr']);
$sth->bindParam(":pe", $array[$i]['pe']);
$sth->bindParam(":bo", $array[$i]['bo']);
$sth->bindParam(":pro",$array[$i]['pro']);
$sth->bindParam(":con",$array[$i]['con']);
$sth->bindParam(":pre",$array[$i]['pre']);
$sth->bindParam(":ca", $array[$i]['ca']);
$sth->bindParam(":de", $array[$i]['de']);
$sth->bindParam(":ke", $array[$i]['ke']);
$sth->bindParam(":da", $array[$i]['da']);
$sth->bindParam(":a", $array[$i]['a'] );
$sth->execute();
$i++;
}
But this code doesn't work. I've also tried to use try-catch(PDOException) for $sth->execute() but it doesn't show me anything.
Why?
Who says "this question is a duplicated" doesn't read really the question. Infact the error was a wrong character: $array[$count]['pr'] = $pfferta['prezzo'] would be been $array[$count]['pr'] = $offerta['prezzo']so I couldn't find an answer in another question.
Try adding some simple checks that things actually worked like this
$res = $sth->execute();
if ( ! $res ) {
echo sprintf('ERROR: %d - %s', $sth->errorCode(), $sth->errorInfo() );
}

$i not incrementing in while loop

Following is my PHP code which is only giving i =0 though in a loop I am incrementing the $i but it always return i as 0 and while loop is only working one time, though my query SELECT * FROM events WHERE DATE(event_date) < CURDATE() is returning 7 records when exectuing in phpmyadmin. Let me know what i am doing wrong here ?
Code -
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/app/'."config.php";
error_reporting(E_ALL);
if( $_POST['number'] == 'all' ) {
$eventArr = array();
$myarray = array();
$query = "SELECT * FROM events WHERE DATE(`event_date`) < CURDATE()";
$result = mysql_query($query);
$i =0;
while($row = mysql_fetch_assoc($result)) {
$eventArr[$i] = array('event_data'=> $row);
// Get image For an event
$event_id = $row['id'];
$query = "SELECT * FROM event_images WHERE event_id = $event_id ORDER BY `uploaded_date` DESC LIMIT 0,1";
$result = mysql_query($query);
$eventImgArr = array();
while($row = mysql_fetch_assoc($result)) {
$eventImgArr[] = $row;
}
$eventArr[$i]['event_image'] = $eventImgArr;
// Get venue details for the event
$venue_id = $row['venue_id'];
$eventVenArr = array();
$query = "SELECT * FROM `venues` WHERE id = $venue_id";
while($row = mysql_fetch_assoc($result)) {
$eventVenArr[] = $row;
}
$eventArr[$i]['venue_detail'] = $eventVenArr;
echo $i, " -- ";
$i++;
}
$myarray = array('response'=>'1','message'=>'Event data', 'data'=>$eventArr);
echo json_encode($myarray);
return;
}
You are re-using the $result variable for the other queries, which is destroying its value needed for the main loop.
P.S. Also, you're not actually executing the query for the venue details.

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

Categories