PHP for loop nested issue - random broke everything - php

I can't find the issue with my code... There's two for loop for building a layout that randomly wraps together the images (from 1 to 3 photos inside a wrapper div)
Sometimes it goes well, but sometimes it gives me the error: call method to null (like the object array can't access the property).
here is the code:
if (isset($get_medias)){
//new gallery structure
$output_gallery_main.='<div id="g-fotografica" class="metro_gallery flip vertical lightbox">';
$indice=0;$loop_counter=0;
for($indice;$indice<count($get_medias);$indice++){
$rand_n=rand(0,2);
if($loop_counter==0) {
$item_size="2x2";
} else { $item_size="1x1"; }
$output_gallery_main.='<div class="tile tile_'.$item_size.' '.$loop_counter.' white">';
for($a=0;$a<=$rand_n;$a++){
$nuovo_indice=$indice+$a;
$m_media=$get_medias[$nuovo_indice];
$titolo=$m_media->get_titolo();
$alt=$m_media->get_alt();
$src=$m_media->get_src();
$thumb_src=$m_media->get_thumb();
$stato=$m_media->get_stato() == 1 ? 'visibile' : 'nascosto';
$ordine=$m_media->get_ordinamento_modello($modello);
if($stato=="visibile"){
//build the structure
$output_gallery_main.='<img src="http://'.$thumb_src.'" alt="'.$alt.'" title="'.$alt.'" data-preview="http://'.$src.'" data-caption="'.$titolo.'" />';
}
}
$output_gallery_main.='</div>';
$indice=$nuovo_indice;
$loop_counter++;
}
$output_gallery_main.='</div>';
Please help me....I'm going crazy!
ps. The $get_media is an array retreived from a db, I printed out the array and it's alway well formed.

Related

Iterate through array when item is found end loop but not found call function

Hi all I have a question. I have an array that is dynamically populated. In the array there are 2 main types of items. Item with file name that equals 27 characters and the rest are either more or less. I am able to separate the 2 two types. The second list is added to a new array called $usedArray. Those items are then iterated through and the file name is substringed from character 0,6 to be used to compare the enduser's input on the page.
if the item is found in that array it will fire a function to send them a text and a email of the the full file name. my problem is if the item is not found until x iterations, it would fire the not found function x amount of times, and if it's not found at all it does the same thing. If I have 99 items that do not match it fire 99 times. to stop from firing I left the not found to just printing not found on the screen. I thought of calling the notfound function outside the loop but do not want it to fire if an items is found
This is my code I have so far
do{
if (substr($val,0,6) == $studentID)
{
$codeFound = substr($val,22,19);
print_r($studentID . ' is found <br /> Their code is ' . $codeFound);
//sendText($phoneNum,$codeFound,$messageMonth);
//sendEmail($emailInfo,$messageMonth,$codeFound);
break 1;
}
else
{
print_r($studentID . " was not found <br />");
}
} while(list(, $val) = each($usedArray));
This is my output
166003 was not found
166003 was not found
166003 was not found
166003 is found
Their code is xxxxxxxxxx
I think you should add a flag to track if you have found something or not:
$item_found = false;
do{
if (substr($val,0,6) == $studentID)
{
$codeFound = substr($val,22,19);
print_r($studentID . ' is found <br /> Their code is ' . $codeFound);
//sendText($phoneNum,$codeFound,$messageMonth);
//sendEmail($emailInfo,$messageMonth,$codeFound);
// item found!
$item_found = true;
break 1;
}
} while(list(, $val) = each($usedArray));
// now check - if `$item_found` is false
// then you can send your NotFoundEmail
if (!$item_found) {
sendNotFoundEmail();
}

How do I validate a PHP integer within a variable?

I have integrated Yelp reviews into my directory site with each venue that has a Yelp ID returning the number of reviews and overall score.
Following a successful MySQL query for all venue details, I output the results of the database formatted for the user. The Yelp element is:
while ($searchresults = mysql_fetch_array($sql_result)) {
if ($yelpID = $searchresults['yelpID']) {
require('yelp.php');
if ( $numreviews > 0 ) {
$yelp = '<img src="'.$ratingimg.'" border="0" /> Read '.$numreviews.' reviews on <img src="graphics/yelp_logo_50x25.png" border="0" /><br />';
} else {
$yelp = '';
}
} //END if ($yelpID = $searchresults['yelpID']) {
} //END while ($searchresults = mysql_fetch_array($sql_result)) {
The yelp.php file returns:
$yrating = $result->rating;
$numreviews = $result->review_count;
$ratingimg = $result->rating_img_url;
$url = $result->url;
If a venue has a Yelp ID and one or more reviews then the output displays correctly, but if the venue has no Yelp ID or zero reviews then it displays the Yelp review number of the previous venue.
I've checked the $numreviews variable type and it's an integer.
So far I've tried multiple variations of the "if ( $numreviews > 0 )" statement such as testing it against >=1, !$numreviews etc., also converting the integer to a string and comparing it against other strings.
There are no errors and printing all of the variables returned gives the correct number of reviews for each property with venues having no ID or no reviews returning nothing (as opposed to zero). I've also compared it directly against $result->review_count with the same problem.
Is there a better way to make the comparison or better format of variable to work with to get the correct result?
EDIT:
The statement if ($yelpID = $searchresults['yelpID']) { is not operating as it should. It is identical to other statements in the file, validating row contents which work correctly for their given variable, e.g. $fbID = $searchresults['fbID'] etc.
When I changed require('yelp.php'); to require_once('yelp.php'); all of the venue outputs changed to showing only the first iterated result. Looking through the venues outputted, the error occurs on the first venue after a successful result which makes me think there is a pervasive piece of code in the yelp.php file, causing if ($yelpID = $searchresults['yelpID']) { to be ignored until a positive result is found (a yelpID in the db), i.e. each venue is correctly displayed with a yelp number of reviews until a blank venue is encountered. The preceding venues' number of reviews is then displayed and this continues for each blank venue until a venue is found with a yelpID when it shows the correct number again. The error reoccurs on the next venue output with no yelpID and so on.
Sample erroneous output: (line 1 is var_dump)
string(23) "bayview-hotel-bushmills"
Bayview Hotel
Read 3 reviews on yelp
Benedicts
Read 3 reviews on yelp (note no var_dump output, this link contains the url for the Bayview Hotel entry above)
string(31) "bushmills-inn-hotel-bushmills-2"
Bushmills Inn Hotel
Read 7 reviews on yelp
I suspect this would be a new question rather than clutter/confuse this one further?
END OF EDIT
Note: I'm aware of the need to upgrade to mysqli but I have thousands of lines of legacy code to update. For now I'm working on functionality before reviewing the code for best practice.
Since the yelp.php is sort of a blackbox; the best explanation for this behavior would be that it only set's those variables if it finds a match. Updating your code to this should fix that:
unset($yrating, $numreviews, $ratingimg, $url);
require('yelp.php');
I also noticed this peculiar if-statement, do you realize that's an assignment or is this a copy/paste error? If you want to test (that's what if is for)
if ($yelpID == $searchresults['yelpID']) {

PHP code to replace certain values in array, code generator

I am trying to write PHP code as a hobby project to basically create a "possible" code generator. The scenario is that we have a list of 25 valid characters that can be used.
Imagine that you have a 25 character code but you have accidentally scratched off the first two characters or three characters at any location in the code. Now we need to find all the possible combinations to try out. I have put all the valid characters into the array below that can be used in the code.
$valid=array("B","C","D","F","G","H","J","K","M","P","Q","R","T","V","W","X","Y","Z",
"2","3","4","6","7","8","9");
$arraylength=count($valid);
The still available or seen characters are input into a text box and in the place where the character is unreadable is left blank and the variable values are fetched.
$char1= $_POST['code1'];
$char2= $_POST['code2'];
$char3= $_POST['code3'];
$char4= $_POST['code4'];
$char5= $_POST['code5'];
$char6= $_POST['code6'];
$char7= $_POST['code7'];
$char8= $_POST['code8'];
$char9= $_POST['code9'];
$char10= $_POST['code10'];
$char11= $_POST['code11'];
$char12= $_POST['code12'];
$char13= $_POST['code13'];
$char14= $_POST['code14'];
$char15= $_POST['code15'];
$char16= $_POST['code16'];
$char17= $_POST['code17'];
$char18= $_POST['code18'];
$char19= $_POST['code19'];
$char20= $_POST['code20'];
$char21= $_POST['code21'];
$char22= $_POST['code22'];
$char23= $_POST['code23'];
$char24= $_POST['code24'];
$char25= $_POST['code25'];
And put into an array...
$jada = array($char1, $char2, $char3, $char4, $char5, $char6, $char7, $char8, $char9, $char10, $char11, $char12, $char13, $char14, $char15
, $char16, $char17, $char18, $char19, $char20, $char21, $char22, $char23, $char24, $char25);
I have been stumped for a while now, the fiddling I have done at the moment is that if a variable is empty then do something (as a test echo or print the possible combinations)
if(!isset($char1) || trim($char1) == ""){
for($x=0;$x<$arraylength;$x++) {
echo $valid[$x];
echo "<br>";
} }
else{
echo ($char1);
}
Can you guys help out?
Saw this still in an open status after many years of hiatus, I figured that I may as well share some information.
In the end I figured it out, you can grab the source here and test it in your own server: https://github.com/Masterkriz/XBOX_Pre-paid_code_fixer

Unable to get stat gathering to work

Using PHP to gather stats from multiple files. Goal is to take the entire first row of data, which is the column name, then take the entire row of data from the row where the first column matches the name specified in the code. These two rows should then be linked to each other, so they can be displayed in a dynamic image.
However, to avoid excessive requests from the external data source, the data is only downloaded once a day by saving it into a json file. The previous day's data is also kept, to perform a difference calculation.
What I'm stuck on is...well, it's not working as intended. The dynamic image does not display and says it cannot be displayed because it contains errors, and the files aren't being created properly. Without any files existing, only the 'old' data file is being created, and the gathered data is saved there in a format that I didn't expect.
Here's the entire PHP code:
<?php
header("Content-Type:image/png");
$root=realpath($_SERVER['DOCUMENT_ROOT']);
function saveTeamData(){
$urls=array('http://www.dc-vault.com/stats/bio.txt','http://www.dc-vault.com/stats/math.txt','http://www.dc-vault.com/stats/misc.txt','http://www.dc-vault.com/stats/overall.txt','http://www.dc-vault.com/stats/phys.txt');
$fullJson=array();
function stats($url){
$json=array();
$team=array("teamName");
$file=fopen($url,'r');
$firstRow=fgetcsv($file,0,"\t");
while($data=fgetcsv($file,0,"\t")){
if(in_array($data[0],$team)){
foreach($firstRow as $indx=>$colName){
if((strpos($colName,'Position')!=0)||(strpos($colName,'Score')!=0)||(strpos($colName,'Team')!=0)){
if(strrpos($colName,'Position')!==false){
$colName=substr($colName,0,strpos($colName,' Position'));
$colName=$colName."Pos";
}else{
$colName=substr($colName,0,strpos($colName,' Score'));
$colName=$colName."Score";
}
$colName=str_replace(' ',',',$colName);
$teamData[$colName]=$data[$indx];
}
}
$json=$teamData;
}
}
fclose($file);
return $json;
}
foreach($urls as $item){
$fullJson=array_merge($fullJson,stats($item));
}
$final_json['teamName']=$fullJson;
$final_json['date']=date("Y-m-d G:i:s",strtotime("11:00"));
$final_json=json_encode($final_json);
file_put_contents("$root/scripts/vaultData.js",$final_json);
return $final_json;
}
if(!file_exists("$root/scripts/vaultData.js")){
$teamData=saveTeamData();
}else{
$teamData=json_decode(file_get_contents("$root/scripts/vaultData.js"));
}
$lastDate=$teamData->date;
$now=date("Y-m-d G:i:s");
$hours=(strtotime($now)-strtotime($lastDate))/3600;
if($hours>=24||!file_exists("$root/scripts/vaultDataOld.js")){
file_put_contents("$root/scripts/vaultDataOld.js",json_encode($teamData));
$teamData=saveTeamData();
}
$team=$teamData->{"teamName"};
$teamOld=json_decode(file_get_contents("$root/scripts/vaultDataOld.js"))->{"teamName"};
$template=imagecreatefrompng("$root/images/vaultInfo.png");
$black=imagecolorallocate($template,0,0,0);
$font='images/fonts/UbuntuMono-R.ttf';
$projects=array();
$subsections=array();
foreach($team as $key=>$val){
$projectName=preg_match("/^(.*)(?:Pos|Score)$/",$key,$cap);
$projectName=str_replace(","," ",$cap[1]);
if(preg_match("/Pos/",$key)){
$$key=(strlen($val)>10?substr($val,0,10):$val);
$delta=$key."Delta";
$$delta=($val - $teamOld->{$key});
$$delta=(strlen($$delta)>5?substr($$delta,0,5):$$delta);
if($projectName!=="Overall"){
if(!in_array($projectName,array("Physical Science","Bio/Med Science","Mathematics","Miscellaneous"))){
$projects[$projectName]["position"]=$$key;
$projects[$projectName]["position delta"]=$$delta*1;
}else{
$subsections[$projectName]["position"]=$$key;
$subsections[$projectName]["position delta"]=$$delta*1;
}
}
}elseif(preg_match("/Score/",$key)){
$$key=(strlen($val)>10?substr($val,0,10):$val);
$delta=$key."Delta";
$$delta=($val - $teamOld->{$key});
$$delta=(strlen($$delta)>9?substr($$delta,0,9):$$delta);
if($projectName!=="Overall"){
if(!in_array($projectName,array("Physical Science","Bio/Med Science","Mathematics","Miscellaneous"))){
$projects[$projectName]["score"]=$$key;
$projects[$projectName]["score delta"]=$$delta;
}else{
$subsections[$projectName]["score"]=$$key;
$subsections[$projectName]["score delta"]=$$delta;
}
}
}
}
$sort=array();
foreach($projects as $key=>$row){
$sort[$key]=$row["score"];
}
array_multisort($sort,SORT_DESC,$projects);
$lastupdated=round($hours,2).' hours ago';
$y=35;
foreach($projects as $name=>$project){
imagettftext($template,10,0,5,$y,$black,$font,$name);
imagettftext($template,10,0,149,$y,$black,$font,$project['position']);
imagettftext($template,10,0,216,$y,$black,$font,$project['position delta']*-1);
imagettftext($template,10,0,257,$y,$black,$font,$project['score']);
imagettftext($template,10,0,331,$y,$black,$font,$project['score delta']);
$y+=20;
}
$y=655;
foreach($subsections as $name=>$subsection){
imagettftext($template,10,0,5,$y,$black,$font,$name);
imagettftext($template,10,0,149,$y,$black,$font,$subsection['position']);
imagettftext($template,10,0,216,$y,$black,$font,$subsection['position delta']*-1);
imagettftext($template,10,0,257,$y,$black,$font,$subsection['score']);
imagettftext($template,10,0,331,$y,$black,$font,$subsection['score delta']);
$y+=20;
}
imagettftext($template,10,0,149,735,$black,$font,$team->{'OverallPos'});
imagettftext($template,10,0,216,735,$black,$font,$OverallPosDelta*-1);
imagettftext($template,10,0,257,735,$black,$font,$OverallScore);
imagettftext($template,10,0,331,735,$black,$font,$OverallScoreDelta);
imagettftext($template,10,0,149,755,$black,$font,$lastupdated);
imagepng($template);
?>
And here is what the data looks like when it is saved:
"{\"teamName\":{\"Folding#HomePos\":\"51\",\"Folding#HomeScore\":\"9994.405407\"},\"date\":\"2014-03-14 11:00:00\"}"
I've omitted most of the data because it just makes things excessively long, and it helps to see the format. Now the reason why its an unexpected output is because I didn't expect trailing slashes to be in it. The older version of this code would output like this:
{"teamName":{"Asteroids#HomePos":"192","Asteroids#HomeScore":"7647.783251"},"date":"2014-03-14 11:00:00"}
So the expected behaviour is to to gather the data from the aforementioned rows in each tab delimited text file, copy the old data into the 'old' data file (vaultDataold), save the new data into the 'current' data file (vaultData), and then display the data from the 'current' file in a dynamic image, along with performing a 'new' minus 'old' calculation on the two files to show the change since the previous day.
Most of this code should work, as I've had it working before in a different way. The issue likely lies somewhere with gathering the row data and saving it, most probably the latter. I'm guessing the slashes are causing the issue.
Turns out that the cause was twofold. Firstly, in my function, I was JSON encoding something that had already been encoded, so when the second file was saved, it appeared as shown in my question. To fix that, I did this:
$final_json['date']=date("Y-m-d G:i:s",strtotime("11:00"));
$encode_json=json_encode($final_json);
file_put_contents("$root/scripts/vaultData.js",$encode_json);
return $final_json;
In addition, as pointed out by another in the comments, I had to add $root to my function, and again within it.

Executing MySQL Queries and Creating Instances several Times within Loop

I have an Web Application that requires SELECT and INSERT Querying to MySQL database and Instantiating a PHP class using new operator almost more that thousand times within a loop. May be there are alternatives to my present logic, but my point is that is there any harm if I carry on this logic?. I don't bother about the time complexity associated with the algorithm presently but **worrying much about if anything goes wrong during transaction or memory usage. I am giving the piece of code for reference
$stm_const = "select ce.TIMETAKEN, qm.QMATTER as STRING1, ce.SMATTER as STRING2 from w_clkexam ce, clkmst cm, qsmst qm where ce.QID=qm.QID and cm.ROLLNO=ce.ROLLNO";
for ($c=0; $c < count($rollnos); $c++) {
$stm3 =$stm_const." "."and ce.ROLLNO='$rollnos[$c]'";
$qry3 = mysql_query($stm3) or die("ERROR 3:".mysql_error());
while($row1 = mysql_fetch_array($qry3)) {
echo $string1=$row1['STRING1'];
echo $string2=$row1['STRING2'];
$phpCompareStrings=new PhpCompareStrings($string2, $string1);
$percent=$phpCompareStrings->getSimilarityPercentage();
$percent2=$phpCompareStrings->getDifferencePercentage();
echo '$string1 and $string2 are '.$percent.'% similar and '.$percent2.'% differnt<br/>';
}// end while
}// end for
Please help, I am waiting for opinions from you so that I can move further. Thanks in advance.
I don't see any problem there. You just get all the rows from database and for each row compare the strings. As you assign the object to the same variable each time, the old object is destroyed before the new object is created. So you have only one instance of the object in memory at all times. The question is what you want to do with the results? Only print them as in your example, or to store the results for further processing?
Anyway, I think it is not possible to optimize your code without modifying the class. If you are using this class, you can try to modify it so that it can accept multiple strings. Using this, you can create only 1 instance of the class and you avoid destroying/creating the object for every row. It will save you some CPU time, but not memory (as at all times, only 1 instance of the class is active).
Untested modification below:
Modify this function inside the class:
function __construct($str1,$str2){
$str1=trim($str1);
$str2=trim($str2);
if($str1==""){ trigger_error("First parameter can not be left blank", E_USER_ERROR); }
elseif($str2==""){ trigger_error("Second parameter can not be left blank", E_USER_ERROR); }
else{
$this->str1=$str1;
$this->str2=$str2;
$this->arr1=explode(" ",$str1);
$this->arr2=explode(" ",$str2);
}
}
To these 2 functions:
function init($str1,$str2){
$str1=trim($str1);
$str2=trim($str2);
if($str1==""){ trigger_error("First parameter can not be left blank", E_USER_ERROR); }
elseif($str2==""){ trigger_error("Second parameter can not be left blank", E_USER_ERROR); }
else{
$this->str1=$str1;
$this->str2=$str2;
$this->arr1=explode(" ",$str1);
$this->arr2=explode(" ",$str2);
}
}
function __construct($str1,$str2){ $this->init($str1,$str2); }
Then create the object outside the loop and only call $phpCompareStrings->init($string2,$string1) inside the loop.

Categories