How to search defined class or variable's location - php

These errors keep coming after changing the PHP website to new server.
1st - Solved by "shaddy"
Notice: Undefined variable: es in /home/musthand/public_html/external/site/header.php on line 2
<?php
if(!is_object($es))
{
require_once('includes/EliteScript.php');
$es = new EliteScript();
$sMemberId = $es->getMemberId();
}
// Get the base URL
$sBaseUrl = $es->getConfig('baseUrl');
$sImageUrl = $es->getConfig('imageUrl');
$sMemberId = $es->getMemberId();
$sUsername = $es->getMemberUsername($sMemberId);
$sIP = $_SERVER['REMOTE_ADDR'];
// Vars we want to pass to the system
$aJSVars = array(
'member_url' => $es->getConfig('memberUrl'),
'base_url' => $es->getCOnfig('baseUrl'),
'image_url' => $es->getConfig('imageUrl'),
'date' => date("F d, Y H:i:s", time()),
);
$ba = new BannerAd();
?>
2nd
Fatal error: Class 'FOrum' not found in /home/musthand/public_html/interface/forum.php on line 33
<?php
global $es;
global $ui;
global $member_id;
global $base_url;
global $member_url;
global $image_url;
global $admin_url;
require_once("includes/EliteScript.php");
$es = new EliteScript();
$ui = new UserInterface();
$es->RequireMember();
$member_id = $es->GetMemberId();
$base_url = $es->GetConfig("baseUrl");
$member_url = $es->GetConfig("memberUrl");
$image_url = $es->GetConfig("imageUrl");
$es->DisplayHeader("Forum", "member.php");
$_REQUEST["do"];
display_main();
$es->DisplayFooter();
function display_main()
{
global $es;
global $ui;
global $member_id;
global $base_url;
global $member_url;
global $image_url;
global $admin_url;
$cur_sign = $es->GetCurrencySign();
$f = new FOrum();
echo "<script>\n</script>\n\n<div class=\"bigHeader\">Forum</div>\n";
echo $ui->GenerateMessageBox("msg", 0, 5);
echo $ui->GenerateErrorBox("err", 0, 5);
echo "\n";
echo $ui->DisplayToolTip("Forum", "Below you can participate in the company forum.");
echo "<br>\n\n\n";
$q = "SELECT * FROM forumSections ORDER BY id";
$r = mysql_query($q);
while( $l = mysql_fetch_array($r) )
{
$l_sid = $l["id"];
$l_sec_name = htmlentitiesi($l["name"]);
echo "<div class=\"header\">";
echo $l_sec_name;
echo "</div>\n<table cellspacing=\"1\" cellpadding=\"0\" border=\"0\" width=\"100%\" class=\"dataTbl\">\n<tr class=\"tblHeader\">\n<td>Forum</td>\n<td width=\"50\" align=\"center\">Topics</td>\n<td width=\"50\" align=\"center\">Replies</td>\n<td width=\"150\" align=\"right\">Last Post Info</td>\n</tr>\n";
$html = NULL;
$qb = "SELECT * FROM forums WHERE sectionId='" . $l_sid . "' ORDER BY id";
$rb = mysql_query($qb);
while( $lb = mysql_fetch_array($rb) )
{
$l_fid = $lb["id"];
$l_name = htmlentitiesi($lb["name"]);
$l_desc = htmlentitiesi($lb["description"]);
$l_topics = $f->GetForumTopicCount($l_fid);
$l_replies = $f->GetForumReplyCount($l_fid);
$html .= "<tr class=\"tblRowA\">\n\t\t\t<td style=\"padding: 5px 0px 5px 5px;\">\n\t\t\t<b>" . $l_name . "</b>\n\t\t\t<div style=\"padding-top: 5px;\">\n\t\t\t" . $l_desc . "\n\t\t\t</div>\n\t\t\t\n\t\t\t</td>\n\t\t\t<td align=\"center\">" . $l_topics . "</td>\n\t\t\t<td align=\"center\">" . $l_replies . "</td>\n\t\t\t<td align=\"right\">" . $l_lastpost . "</td>\n\t\t\t</tr>";
}
echo $html;
echo "</table>\n\n";
}
echo "\n\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n<br>\n\n\n\n\n\n<div class=\"header\">News & Updates</div>\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n";
$html = NULL;
$q = "SELECT * FROM news ORDER BY added DESC,id DESC LIMIT 5";
$r = mysql_query($q);
while( $l = mysql_fetch_array($r) )
{
$l_id = $l["id"];
$l_title = htmlentitiesi($l["title"]);
$l_date = date("M jS", strtotime($l["added"]));
$html .= "<tr class=\"sepLine\"><td width=\"20\"><img src=\"" . $image_url . "/note.png\" width=\"16\" height=\"16\"></td><td>" . $l_title . " <i style=\"color:gray;\">(" . $l_date . ")</i></td></tr>\n";
}
if( !$html )
{
$html = "<tr class=\"sepLine\"><td style=\"color: gray;\">Currently no news and updates...</td></tr>";
}
echo $html;
echo "</table>\n<br>\n\n<div class=\"header\">Account Summary</div>\n\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n<tr class=\"sepLine\">\n<td width=\"20\"><img src=\"";
echo $image_url;
echo "/user.png\" width=\"16\" height=\"16\"></td>\n<td width=\"175\"><b>Member Info:</b></td>\n<td>";
echo $username;
echo " (#";
echo $member_id;
echo ") <i>(<a href=\"mailto:";
echo $email;
echo "\">";
echo $email;
echo "</a>)</i></td>\n<td align=\"right\"><a href=\"";
echo $member_url;
echo "/preferences.php\">[Preferences]</a></td>\n</tr>\n</table>\n\n<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\" width=\"100%\">\n<tr><td class=\"toolTip\">\nYou must ";
echo $req_text;
echo " before participating.</td></tr>\n</table>\n\n\n\n\n<div class=\"header\">Current Active ";
echo $token_label;
echo "s</div>\n\n<table cellspacing=\"1\" cellpadding=\"0\" border=\"0\" width=\"100%\" class=\"dataTbl\">\n<tr class=\"tblHeader\">\n<td width=\"50\">ID</td>\n<td>Type</td>\n<td width=\"40\">Units</td>\n<td width=\"80\">Amount</td>\n<td width=\"150\">Earned So Far</td>\n<td width=\"80\">Created</td>\n</tr>\n\n";
$tok_types = $es->GetConfig("tokenTypes");
$html = NULL;
$tblClass = "tblRowA";
$q = "SELECT * FROM tokens WHERE memberId='" . $member_id . "' AND status = 'ACTIVE' ORDER BY created DESC,id DESC";
$r = mysql_query($q);
while( $l = mysql_fetch_array($r) )
{
$l_id = $l["id"];
$l_type = $l["type"];
$tok_arr = $tok_types[$l_type];
$l_name = htmlentitiesi($tok_arr["name"]);
$l_amt = $l["amount"];
$l_esf = $l["earnedSoFar"];
$l_exp_type = $l["expireType"];
$l_exp_val = $l["expiresOnValue"];
$l_created = $l["createdDate"];
$l_lastroi = $l["lastRoiDate"];
$l_incycle = $l["inCycle"];
$l_status = $l["status"];
if( $l_status == "ACTIVE" )
{
$lb_status = "<span style=\"color: darkgreen;\">Active</span>";
}
else
{
if( $l_status == "EXPIRED" )
{
$lb_status = "<span style=\"color: red;\">Expired</span> as of " . date("M jS, y", strtotime($l["expiresDate"]));
}
}
if( $l_created == $l_lastroi && $l_incycle <= 1 )
{
$l_lastearn_text = "Never";
}
else
{
$l_lastearn_text = date("M jS, y", strtotime($l_lastroi));
}
$l_units = sprintf("%d", $l["units"]);
$l_earned_per = sprintf("%.2f", $l_esf / $l_amt * 100);
$earned_per_style = "color: gray;";
if( 100 < $l_earned_per )
{
$earned_per_style = "color: darkgreen;";
}
$l_created_date = date("M jS, y", $l["created"]);
if( $l_exp_type == "value" )
{
$l_exp_text = sprintf("%.2f", $l_exp_val) . "%";
$l_exp_text .= " <i>(" . $cur_sign . sprintf("%.2f", $l_amt * $l_exp_val / 100) . ")</i>";
}
else
{
if( $l_exp_type == "date" )
{
$l_exp_text = date("M jS, y", $l["expires"]);
}
else
{
if( $l_exp_type == "never" )
{
$l_exp_text = "No Set Expiry";
}
}
}
$lb_amt = number_format($l_amt, 2);
$lb_esf = number_format($l_esf, 2);
$html .= "\n\t\t<tr class=\"" . $tblClass . "\">\n\t\t<td>#" . $l_id . "</td>\n\t\t<td><b>" . $l_name . "</b></td>\n\t\t\n\t\t<td>" . $l_units . "</td>\n\t\t<td>" . $cur_sign . $lb_amt . "</td>\n\t\t<td>" . $cur_sign . $lb_esf . " <i style=\"" . $earned_per_style . "\">(" . $l_earned_per . "%)</i></td>\n\t\t<td>" . $l_created_date . "</td>\n\t\t</tr>\n\t\t<tr class=\"" . $tblClass . "\">\n\t\t<td colspan=\"6\" style=\"padding-left: 20px;\">\n\t\t\n\t\t<table cellspacing=\"0\" cellpadding=\"0\" border=\"0\">\n\t\t<tr><td width=\"170\">\n\t\t<u>Last Earn Date:</u> " . $l_lastearn_text . "\n\t\t</td><td width=\"190\">\n\t\t<u>Expires:</u> " . $l_exp_text . "\n\t\t</td><td>\n\t\t<u>Status:</u> " . $lb_status . "\n\t\t</td></tr>\n\t\t</table>\n\t\t\n\t\t</td>\n\t\t</tr>";
$tblClass = $tblClass == "tblRowA" ? "tblRowB" : "tblRowA";
}
if( !$html )
{
$html .= "<tr class=\"" . $tblClass . "\"><td colspan=\"7\"><span style=\"color: gray;\">Currently no active " . $token_label . "s...</span></td></tr>";
}
echo $html;
echo "</table>\n\n<br><br>\n\n";
}
?>
They used to work fine on old server, I don't know what's up with these errors on new one.
They're defined somewhere in somefile, there are 800+ files and it's hard to search in each and every.
Is there any way that we can make the server look of the actual file where these classes or variables were defined?

Your code was never working well. It is bad written. The reason you did not see errors, in your old server is that you had lower error reporting or the whole error reporting was turned off. When you are developing something you should always develop with turned on error reporting, so you can see your mistakes.
The first problem is here
if(!is_object($es)) {
You check directly if $es is object, but this is wrong, because this statement is at the top of the file, and $es will be aways undefined unless you import it from the global scope, like this:
global $es;
if(!is_object($es)) {
Your second error is because you have referenced wrongly the Forum class:
$f = new FOrum();
I suppose it should be:
$f = new Forum();

Related

PHP while to populate table with function to repeat data calculation

In a contract management tool I'm trying to populate a table from a PHP query.
The function is working properly until I use it in the while to calculate several dates during the same while loop.
FUNCTION CODE:
function calculo_data($data_calculo){
if($data_calculo == 0 ){
$result_datas = "NÂO aplicavel ";
echo $result_datas;
} else {
$hoje = date_create();
$data_calculo_date = date_create($data_calculo);
$diff = date_diff( $hoje, $data_calculo_date );
$meses = (($diff->format('%y')*12)+$diff->format('%m'));
$dias = $diff->days;
if($data_calculo_date < $hoje){
$result_datas = "não aplicavel ";
echo $result_datas;
} elseif($meses >=1 ) {
$result_datas = $meses . " meses ";
echo $result_datas;
} else {
$result_datas = $dias . " dias ";
echo $result_datas;
};
;
};
};
TABLE CODE:
while ($row_detalhes = mysqli_fetch_assoc($result_listagem_contratos)){
$listagem_cliente_ref = $row_detalhes['PkContrato'];
$listagem_cliente_cliente = $row_detalhes['ClienteNome'];
$listagem_cliente_inicio = $row_detalhes['ContratoDataInicio'];
$listagem_cliente_fim = $row_detalhes['ContratoDataFim'];
$listagem_cliente_senhorio = $row_detalhes['ContratoPreAvisoSenhorio'];
$listagem_cliente_inquilino = $row_detalhes['ContratoPreAvisoInquilino'];
$listagem_cliente_break = $row_detalhes['ContratoDataBreak'];
echo '<tr>';
echo '<td>' . $listagem_cliente_ref .'</td>';
echo '<td>' . $listagem_cliente_cliente .'</td>';
echo '<td>' . $listagem_cliente_inicio .'</td>';
echo '<td>' . $listagem_cliente_fim .' ( ' . calculo_data($listagem_cliente_fim) . ' )</td>';
echo '<td>' . $listagem_cliente_senhorio .' ( ' .calculo_data($listagem_cliente_senhorio) . ' )</td>';
echo '<td>' . $listagem_cliente_inquilino .' ( ' . calculo_data($listagem_cliente_inquilino) . ' )</td>';
echo '<td>' . $listagem_cliente_break .' ( ' . calculo_data($listagem_cliente_break) . ' )</td>';
echo '<td><a href="detalhe_contrato.php?id='. $listagem_cliente_ref . '">
<span class="glyphicon glyphicon-file" style="color:black"></span>
</a></td<>';
The result is the table showing at least part of the results but in the wrong position as in the picture!
It's because you echo directly in the function. It should return the values, not echo them:
function calculo_data($data_calculo){
if($data_calculo == 0 ){
$result_datas = "NÂO aplicavel ";
return $result_datas;
} else {
$hoje = date_create();
$data_calculo_date = date_create($data_calculo);
$diff = date_diff( $hoje, $data_calculo_date );
$meses = (($diff->format('%y')*12)+$diff->format('%m'));
$dias = $diff->days;
if($data_calculo_date < $hoje){
$result_datas = "não aplicavel ";
return $result_datas;
} elseif($meses >=1 ) {
$result_datas = $meses . " meses ";
return $result_datas;
} else {
$result_datas = $dias . " dias ";
return $result_datas;
}
}
}
There were also some ; too much that I removed.

How to xml to php nested arrays?

I 'm a total PHP beginner and need some help :-)
Have this xml:
http://pastebin.com/ZSpNPhXH
And this scrypt:
<?php
// Retrieve XML File
$file = file_get_contents('livescore-feed.xml');
// Parse XML with SimpleXML
$livescore_data = new SimpleXMLElement($file);
foreach ($livescore_data->league as $league) {
echo "<table class='table table-striped table-bordered table-condensed'>";
echo "<thead><tr><th colspan='6' id='league'>" . $league->attributes()->name . "</th></tr></thead>";
echo "<tbody>";
foreach ($league->match as $match) {
$status = $match->attributes()->status;
$home = $match->home->attributes()->name;
$away = $match->away->attributes()->name;
$score = $match->home->attributes()->goals . " - " . $match->away->attributes()->goals;
// If match not yet started, there will be a ":" in 'status' attribute
if (strpos($match->attributes()->status,':') !== false) {
$score = "-";
}
echo "<tr><td class='status' id='match'>" . $status . "</td><td id='match' colspan='2'>" .
$home . "</td><td class='score' id='match'>" . $score . "</td><td id='match' colspan='2'>" .
$away . "</td>
</tr>";
}
echo "</tbody></table>";
}
?>
How to show/parse "events" also
Thank you very much for your help and suggestions
In the same way you parse other data!
foreach( $livescore_data->league as $league )
{
(...)
foreach( $league->match as $match )
{
(...)
# ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
foreach( $match->events->event as $event )
{
echo $event['assist'] . '<br>';
echo $event['player'] . '<br>';
(...)
}
}
}
You have to perform a loop through $match->events->event and you can get each <event> attribute using $event[attribute] syntax. So, $event['extra_min'], $event['minute'], etc...
You have only to adapt the code to your table structure.

Reading Line by Line Using PHP Via JSON String

I am trying to create a PHP function which will allow me to read selected lines from a text file using a JSON string. The JSON string consists of two numbers separated by a comma. The first number is the line I want to seek, and the second is the number of lines to read going downward.
For example, I have this sentence in a separate text file:
A diving spiral attack in which Pikachu head butts downward while
being surrounded by electricity.
(If you're wondering, this is part of my upcoming fan site, still under construction).
The sentence starts at line 6, and uses up 2 lines. So in my JSON file, I would write "6,2". The explode() command is ran using the comma as the delimiter, allowing me to store these number into two individual variables, $start and $length.
$result = explode(",", $sample); // In JSON string, $sample is $i["desc"]
$start = $result[0];
$length = $result[1];
With the variables now in place, the following lines will then be called to perform the actual line-by-line extraction.
$file = new SplFileObject("pikachu/pikachu.txt");
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
echo "$file";
}
I did a test of my script using a direct call instead of through JSON parsing. That worked. But when I tried to use the JSON string, I ended up with both a Runtime and a Fatal Error.
How do I fix the scripts so that I can use the JSON string as markers for seeking lines from an external text to print while avoiding the Runtime and Fatal Errors?
(EDIT: The problem became too difficult for me to fix, so I've decided to ditch the line-by-line seek feature for now. I will revisit this on a later date. I will leave the code below for archival purposes.)
character.php
<?php
$name = $_GET['name'];
// Step 1: Get the name from the previous page and store it.
$file = file_get_contents("characters/$name/$name.json");
// Step 2: Use the name to find a JSON file for the character (We'll do the moves list later).
$json = json_decode($file, true);
// Step 3: Decode the JSON file
$character = $json["character"][0]["name"];
$group = $json["character"][0]["group"];
$series = $json["character"][0]["series"];
$story = $json["character"][0]["story"];
$snapback = $json["character"][0]["snapback"];
$interrupt = $json["character"][0]["interrupt"];
$hiddenpow = $json["character"][0]["hiddenpow"];
$disrupt = $json["character"][0]["disrupt"];
$assist1 = $json["character"][0]["assist1"];
$assist2 = $json["character"][0]["assist2"];
$assist3 = $json["character"][0]["assist3"];
$counter = $json["character"][0]["counter"];
$bros = $json["character"][0]["bros"];
$party = $json["character"][0]["party"];
$ground = $json["character"][0]["ground"];
$jump = $json["character"][0]["jump"];
$superjump = $json["character"][0]["superjump"];
$launcher = $json["character"][0]["launcher"];
$altlaunch = $json["character"][0]["altlaunch"];
$acfinisher = $json["character"][0]["acfinisher"];
// Step 4: Retrieve variables and store them for use
echo "<HTML>\n";
echo "<HEAD>\n";
echo "<TITLE>Marvel & Capcom vs. Pokemon: $character</TITLE>\n\n";
echo "<LINK rel=\"stylesheet\" type=\"text/css\" href=\"http://fonts.googleapis.com/css?family=Roboto\">\n";
echo "<LINK rel=\"stylesheet\" type=\"text/css\" href=\"http://fonts.googleapis.com/css?family=Open+Sans\">\n";
echo "<LINK rel=\"stylesheet\" type=\"text/css\" href=\"media/style.css\">\n";
echo "<SCRIPT type=\"text/javascript\" src=\"media/tabs.js\"></SCRIPT>\n";
echo "<SCRIPT type=\"text/javascript\">\n";
echo "function toggle_visibility(id) {\n";
echo " var movename = id.nextSibling.nextSibling;\n";
echo " if(movename.style.display == \"block\")\n";
echo " movename.style.display = \"none\";\n";
echo " else\n";
echo " movename.style.display = \"block\";\n";
echo "}\n";
echo "</SCRIPT>";
echo "</HEAD>\n\n";
echo "<BODY onload=\"init()\">\n\n";
// Step 5: The HTML stuff begins
echo "<TABLE id=\"Character\">\n";
echo " <TR>\n";
echo " <TD class=\"Name\">" . strtoupper($character) . "</TD>\n";
echo " <TD class=\"Image\" rowspan=\"4\"><IMG src=\"characters/$name/$name.jpg\"></TD></TR>\n";
echo " <TR>\n";
echo " <TD class=\"Series\">Series: $series</TD></TR>\n";
echo " <TR>\n";
echo " <TD class=\"Story\">$story</TD></TR>\n";
// Step 6: Write the variables to the file
echo " <TR>\n";
echo " <TD style=\"vertical-align: top\">\n";
echo " <TABLE id=\"$group\">\n";
function moverw ($move) {
$subfollow = "FOLLOW>>";
$follow = "FOLLOW>";
if (strpos($move,$subfollow) !== false)
$move .= " (followup)";
else if (strpos($move,$follow) !== false)
$move .= " (followup)";
$move = str_replace("FOLLOW>>", "<IMG class=\"Followup\" src=\"images/follow.png\" style=\"text-indent: 5px\"> ", $move);
$move = str_replace("FOLLOW>", "<IMG class=\"Followup\" src=\"images/follow.png\"> ", $move);
return ($move);
}
function descrw ($desc,$name) {
$result = explode(",", $desc);
$start = $result[0];
$length = $result[1];
$file = new SplFileObject("characters/$name/$name.txt");
$result = "";
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
$result .= $file;
}
return($result);
}
function commrw ($command) {
$command = str_replace("AM,", "<IMG title=\"Assist Mode\" src=\"images/assist.gif\"> ", $command);
$command = str_replace("SM,", "<IMG title=\"Single Mode\" src=\"images/single.gif\"> ", $command);
$command = str_replace("BRAWL,", "<IMG title=\"Super Smash Brawl\" src=\"images/brawl.png\"> ", $command);
$command = str_replace("uf,", "<IMG class=\"Arrow\" src=\"images/uf.png\">", $command);
$command = str_replace("df,", "<IMG class=\"Arrow\" src=\"images/df.png\">", $command);
$command = str_replace("ub,", "<IMG class=\"Arrow\" src=\"images/ub.png\">", $command);
$command = str_replace("db,", "<IMG class=\"Arrow\" src=\"images/db.png\">", $command);
$command = str_replace("u,", "<IMG class=\"Arrow\" src=\"images/u.png\">", $command);
$command = str_replace("f,", "<IMG class=\"Arrow\" src=\"images/f.png\">", $command);
$command = str_replace("d,", "<IMG class=\"Arrow\" src=\"images/d.png\">", $command);
$command = str_replace("b,", "<IMG class=\"Arrow\" src=\"images/b.png\">", $command);
$command = str_replace("+", "<IMG class=\"Plus\" src=\"images/plus.png\">", $command);
$command = str_replace("AP", "<IMG class=\"Button\" src=\"images/punch.png\">", $command);
$command = str_replace("AK", "<IMG class=\"Button\" src=\"images/kick.png\">", $command);
$command = str_replace("A1", "<IMG class=\"Button\" title=\"Assist 1\" src=\"images/assist1.png\">", $command);
$command = str_replace("A2", "<IMG class=\"Button\" title=\"Assist 2\" src=\"images/assist2.png\">", $command);
$command = str_replace("AB", "<IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\">", $command);
$command = str_replace("LP", "<IMG class=\"Button\" title=\"Jab\" src=\"images/jab.png\">", $command);
$command = str_replace("LK", "<IMG class=\"Button\" title=\"Short\" src=\"images/short.png\">", $command);
$command = str_replace("MP", "<IMG class=\"Button\" title=\"Strong\" src=\"images/strong.png\">", $command);
$command = str_replace("MK", "<IMG class=\"Button\" title=\"Forward\" src=\"images/forward.png\">", $command);
$command = str_replace("HP", "<IMG class=\"Button\" title=\"Fierce\" src=\"images/fierce.png\">", $command);
$command = str_replace("HK", "<IMG class=\"Button\" title=\"Roundhouse\" src=\"images/roundhouse.png\">", $command);
$command = str_replace("FOLLOW>>", "<IMG class=\"Followup\" src=\"images/follow.png\" style=\"text-indent: 5px\"> ", $command);
$command = str_replace("FOLLOW>", "<IMG class=\"Followup\" src=\"images/follow.png\"> ", $command);
$command = str_replace("degrees", "°", $command);
return ($command);
}
function typerw ($type) {
$type = str_replace("BUG.", "<IMG src=\"images/bug.png\">", $type);
$type = str_replace("CYBER.", "<IMG src=\"images/cyber.png\">", $type);
$type = str_replace("DARK.", "<IMG src=\"images/dark.png\">", $type);
$type = str_replace("DRAGON.", "<IMG src=\"images/dragon.png\">", $type);
$type = str_replace("ELECTRIC.", "<IMG src=\"images/electric.png\">", $type);
$type = str_replace("FAIRY.", "<IMG src=\"images/fairy.png\">", $type);
$type = str_replace("FIGHTING.", "<IMG src=\"images/fighting.png\">", $type);
$type = str_replace("FIRE.", "<IMG src=\"images/fire.png\">", $type);
$type = str_replace("FLYING.", "<IMG src=\"images/flying.png\">", $type);
$type = str_replace("GHOST.", "<IMG src=\"images/ghost.png\">", $type);
$type = str_replace("GRASS.", "<IMG src=\"images/grass.png\">", $type);
$type = str_replace("GROUND.", "<IMG src=\"images/ground.png\">", $type);
$type = str_replace("ICE.", "<IMG src=\"images/ice.png\">", $type);
$type = str_replace("LIGHT.", "<IMG src=\"images/light.png\">", $type);
$type = str_replace("NORMAL.", "<IMG src=\"images/normal.png\">", $type);
$type = str_replace("PSYCHIC.", "<IMG src=\"images/psychic.png\">", $type);
$type = str_replace("STEEL.", "<IMG src=\"images/steel.png\">", $type);
$type = str_replace("WATER.", "<IMG src=\"images/water.png\">", $type);
return ($type);
}
function noterw ($note) {
$note = str_replace(".AM.", "<IMG title=\"Assist Mode\" src=\"images/assist.gif\"> ", $note);
$note = str_replace(".SM.", "<IMG title=\"Single Mode\" src=\"images/single.gif\"> ", $note);
$note = str_replace(".HP.", "<IMG class=\"HiddenPower\" title=\"Hidden Power\"src=\"images/hiddenpower.png\">", $note);
return ($note);
}
foreach ($json["character"][0]["moves"] as $i) {
if ($i["flag"] == "normal") {
$move = strtoupper($i["move"]);
$desc = $i["desc"];
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Normal\">" . moverw($move) . "\n";
echo " <DIV class=\"Details\">" . descrw($desc,$name) . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
if ($i["flag"] == "special") {
$move = strtoupper($i["move"]);
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Special\">" . moverw($move) . "\n";
echo " <DIV class=\"Details\">" . $i["desc"] . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
if ($i["flag"] == "hyper") {
$move = strtoupper($i["move"]);
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Hyper\">" . moverw($move) . "\n";
echo " <DIV class=\"Details\">" . $i["desc"] . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
if ($i["flag"] == "final") {
$move = strtoupper($i["move"]);
$command = $i["comm"];
$type = $i["type"];
$note = $i["note"];
echo " <TR>\n";
echo " <TD class=\"MoveName Final\">" . moverw($move) . "\n";
echo " <DIV id=\"Final\" class=\"Details\">" . $i["desc"] . "</DIV></TD>\n";
echo " <TD class=\"Command\">" . commrw($command) . "</TD>\n";
echo " <TD class=\"Type\">" . typerw($type) . "</TD>\n";
echo " <TD class=\"Note\">" . noterw($note) . "</TD></TR>\n";
}
}
// Step 7: Write the moves. When Command and Type are parsed, execute respective rewriters. Saves me from typing lots, hun ;)
echo " </TABLE></TD></TR>\n";
echo " <TR>\n";
echo " <TD colspan=\"2\">\n";
echo " <UL id=\"tabs\">\n";
echo " <LI>SINGLE MODE</LI>\n";
echo " <LI>ASSIST MODE</LI>\n";
echo " <LI>COMBO PROFILE</LI>\n";
echo " <LI>ATTACK PROFILE</LI></UL>\n";
echo " <DIV class=\"tabContent\" id=\"Single\">\n";
echo " <TABLE id=\"Single\" border=1>\n";
echo " <TR>\n";
echo " <TH>Snapback:</TH>\n";
echo " <TD>$snapback</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Interrupt:</TH>\n";
echo " <TD>$interrupt</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Hidden Power:</TH>\n";
echo " <TD>$hiddenpow</TD></TR>\n";
echo " <TR>\n";
echo " <TH class=\"Header Rumble\"colspan=\"2\">RUMBLE CHART</TH></TR>\n";
echo " <TR>\n";
echo " <TD colspan=\"2\"></TH></TR></TABLE></DIV>\n";
echo " <DIV class=\"tabContent\" id=\"Assist\">\n";
echo " <TABLE id=\"Assist\" border=1>\n";
echo " <TR>\n";
echo " <TH>Disrupt:</TH>\n";
echo " <TD>$disrupt</TD></TR>\n";
echo " <TR>\n";
echo " <TH colspan=2>Assist Attacks</TH></TR>\n";
echo " <TR>\n";
echo " <TH><IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\"></TH>\n";
echo " <TD>$assist1</TD></TR>\n";
echo " <TR>\n";
echo " <TH><IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\"><IMG class=\"Plus\" src=\"images/plus.png\"><IMG class=\"Button\" title=\"Fierce\" src=\"images/fierce.png\"></TH>\n";
echo " <TD>$assist2</TD></TR>\n";
echo " <TR>\n";
echo " <TH><IMG class=\"Button\" title=\"Assist\" src=\"images/assist.png\"><IMG class=\"Plus\" src=\"images/plus.png\"><IMG class=\"Button\" title=\"Roundhouse\" src=\"images/roundhouse.png\"></TH>\n";
echo " <TD>$assist3</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Cross-Over Counter:</TH>\n";
echo " <TD>$counter</TD></TR>\n";
echo " <TR>\n";
echo " <TH colspan=2>Super Smash Melee</TH></TR>\n";
echo " <TR>\n";
echo " <TH>Bros. Attack:</TH>\n";
echo " <TD>$bros</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Party Attack:</TH>\n";
echo " <TD>$party</TD></TR></TABLE></DIV>\n";
echo " <DIV class=\"tabContent\" id=\"Combo\">\n";
echo " <TABLE id=\"Combo\" border=1>\n";
echo " <TR>\n";
echo " <TH colspan=2>???</TH></TR>\n";
echo " <TR>\n";
echo " <TH>Ground:</TH>\n";
echo " <TD>$ground</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Jump:</TH>\n";
echo " <TD>$jump</TD></TR>\n";
echo " <TR>\n";
echo " <TH>Super Jump:</TH>\n";
echo " <TD>$superjump</TD></TR>\n";
echo " <TR>\n";
echo " <TH colspan=2></TH></TR>\n";
echo " <TR>\n";
echo " <TH>Launcher:</TH>\n";
echo " <TD>$launcher</TD></TR>\n";
if ($altlaunch != null) {
echo " <TR>\n";
echo " <TH>Alternate Launch:</TH>\n";
echo " <TD>$altlaunch</TD></TR>\n";
}
echo " <TR>\n";
echo " <TH>AC Finishers:</TH>\n";
echo " <TD>$acfinisher</TD></TR></TABLE></DIV>\n";
echo " <DIV class=\"tabContent\" id=\"Attack\">\n";
echo " $test 4\n";
echo " </DIV>\n";
echo " </TD></TR></TABLE></TD></TR></TABLE>\n\n";
echo "</BODY></HTML>";
?>
$name.json, where $name is the name of the character (using pikachu as demo):
{"character":[
{
"name":"Pikachu",
"group":"Pokemon",
"series":"Pokemon",
"story":"To-do...",
"moves":[
{
"flag":"normal",
"move":"Discharge",
"desc":"3,2",
"comm":"Press HP (crouch) (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"normal",
"move":"Electric Screw",
"desc":"6,2",
"comm":"Tilt d,+HP [air]",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"normal",
"move":"Tackle",
"desc":"9,1",
"comm":"Tap f, , f,",
"type":"NORMAL.",
"note":"Notes"
},
{
"flag":"special",
"move":"Quick Attack",
"desc":"11,2",
"comm":"Tap any direction and Press AP (air)",
"type":"ELECTRIC.FIGHTING.",
"note":"Notes"
},
{
"flag":"special",
"move":"Thunder Jolt",
"desc":"14",
"comm":"Motion d,df,f,+AP",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"special",
"move":"Electro Ball",
"desc":"16,2",
"comm":"Motion d,df,f,+AP [air]",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"special",
"move":"Thunder",
"desc":"19,2",
"comm":"Motion f,d,df,+AP (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"special",
"move":"Electric Chair",
"desc":"22,2",
"comm":"Motion f,df,d,db,b,+AP",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"hyper",
"move":"Thunder Shock",
"desc":"25,2",
"comm":"Motion d,df,f,+APAP (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"hyper",
"move":"Thunder Bolt",
"desc":"28,1",
"comm":"Motion d,df,f,+AKAK (air)",
"type":"ELECTRIC.",
"note":"Notes"
},
{
"flag":"hyper",
"move":"Skull Bash",
"desc":"30,2",
"comm":"Motion d,db,b,+APAP (air)",
"type":"ELECTRIC.FIGHTING.",
"note":"Notes"
},
{
"flag":"final",
"move":"Volt Tackle",
"desc":"33,2",
"comm":"Motion d,df,f,d,df,f,+APAP (air)",
"type":"ELECTRIC.",
"note":"Notes"
}],
"snapback":"Crouching Forward",
"interrupt":"Thunder Jolt, Thunder",
"hiddenpow":"Hidden Power Enhancements (Line per line lookup)",
"disrupt":"Thunder",
"assist1":"Thunder Jolt",
"assist2":"Thunder",
"assist3":"Quick Attack",
"counter":"Thunder",
"bros":"Skull Bash",
"party":"Thunder Bolt",
"ground":"Punch to Kick",
"jump":"Punch to Kick",
"superjump":"Zig Zag",
"launcher":"Standing Roundhouse",
"altlaunch":"Crouching Strong",
"acfinisher":"Discharge, Electric Screw, Quick Attack, Electro Ball, Thunder, Thunder Shock, Thunder Bolt, Skull Bash"
}
]}
The problem is in this function, and has nothing to do with your use of JSON. It's just a simple variable scope issue.
function descrw ($desc) {
$result = explode(",", $desc);
$start = $result[0];
$length = $result[1];
$file = new SplFileObject("$name/$name.txt");
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
echo "$file";
}
return(0);
}
The variable $name is not defined, so it's trying to open the file /.txt. You need to change the function so it takes $name as an argument. And since the caller of descrw expects it to return a string so that it can be concatenated, descrw shouldn't do its own echo.
function descrw ($desc, $name) {
$result = explode(",", $desc);
$start = $result[0];
$length = $result[1];
$file = new SplFileObject("$name/$name.txt");
$result = '';
for ($i = $start; $i <= ($start+$length); $i++) {
$file->seek($i-1);
$result .= $file;
}
return($result);
}
Then change the place where it's called to pass the argument:
echo " <DIV class=\"Details\">" . descrw($desc, $name) . "</DIV></TD>\n";

Looping through every record from database

I've searched on the internet for this, and questions here on SO but mostly are using something else than PHP. So i will ask my own question.
What i need to do is make a button that will print out (read literally print, as in downloading a word document with all details on it) every record from the database.
The ID is named 'abstract_id'.
What i'm going to show you next is the print button from all pages, what i mean by this is if you click on said button it will print everything from that specific page:
$abstract_id = addslashes($_POST['abstract_id']);
//Here i connect to the database//
$query = "SELECT * FROM abstracts WHERE abstract_id = '$abstract_id'";
$result = mysql_query($query);
$i = 0;
$title = mysql_result($result,$i,"title");
$author[1] = mysql_result($result,$i,"author1");
$organization[1] = mysql_result($result,$i,"organization1");
$author[2] = mysql_result($result,$i,"author2");
$organization[2] = mysql_result($result,$i,"organization2");
$author[3] = mysql_result($result,$i,"author3");
$organization[3] = mysql_result($result,$i,"organization3");
$author[4] = mysql_result($result,$i,"author4");
$organization[4] = mysql_result($result,$i,"organization4");
$author[5] = mysql_result($result,$i,"author5");
$organization[5] = mysql_result($result,$i,"organization5");
$author[6] = mysql_result($result,$i,"author6");
$organization[6] = mysql_result($result,$i,"organization6");
$format = mysql_result($result,$i,"format");
$language = mysql_result($result,$i,"language");
$presenter = mysql_result($result,$i,"presenter");
$background = mysql_result($result,$i,"background");
$purpose = mysql_result($result,$i,"purpose");
$methods = mysql_result($result,$i,"methods");
$findings = mysql_result($result,$i,"findings");
$conclusion = mysql_result($result,$i,"conclusion");
$word_count = mysql_result($result,$i,"word_count");
$name = mysql_result($result,$i,"name");
$email1 = mysql_result($result,$i,"email1");
$email2 = mysql_result($result,$i,"email2");
$phone1 = mysql_result($result,$i,"phone1");
$phone2 = mysql_result($result,$i,"phone2");
$fax = mysql_result($result,$i,"fax");
$address = mysql_result($result,$i,"address");
$country = mysql_result($result,$i,"country");
$topic = mysql_result($result,$i,"topic");
$master_status = mysql_result($result, $i, "master_status");
$last_edit = mysql_result($result,$i,"last_edit");
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=abstract_" . $abstract_id . ".doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
echo "<p><b>PCNE Abstract</b> $abstract_id</p>";
echo "<h1>$title</h1>";
echo "<b>";
for ($i = 1; $i<= 6; $i++) {
echo ((!empty($author[$i-1]) && !empty($author[$i])) ? ", " : "") ;
echo ((!empty($author[$i])) ? $author[$i] . "<sup>" . $i . "</sup>" : "") ;
}
echo ".</b>";
echo "<br>";
for ($i = 1; $i<= 6; $i++) {
if (!empty($author[$i])) {
echo (!empty($organization[$i]) && !empty($organization[$i-1])) ? ". " : "";
echo ((!empty($organization[$i])) ? "<sup>" . $i . "</sup>" . $organization[$i]: "") ;
}
}
echo (!empty($email1)) ? " (" . $email1 . ")" : "";
echo "<br>";
echo "<br>";
echo "<b>Background</b> ";
echo "$background<br>";
echo "<b>Purpose</b> ";
echo "$purpose<br>";
echo "<b>Method</b> ";
echo "$methods<br>";
echo "<b>Findings</b> ";
echo "$findings<br>";
echo "<b>Conclusion</b> ";
echo "$conclusion<br>";
echo "</body>";
echo "</html>";
Now, this works fine, but i need a same working button which does almost the same, but instead of printing out 1 record it should print all. So all i basically need is a foreach or while loop that goes through every abstract_id.
It's been ages since i last programmed php, so i appreciate any help!
If you need any clarification, feel free to ask.
First you don't need your 30 lines of mysql_result, just use mysql_fetch_assoc to get all values in associative array.
Then you just have to do a while ( $line = mysql_fetch_assoc($query) ), see above :
header("Content-type: application/vnd.ms-word");
header("Content-Disposition: attachment;Filename=abstract_all.doc");
echo "<html>";
echo "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=Windows-1252\">";
echo "<body>";
$query = mysql_query("SELECT * FROM abstracts WHERE 1") or die(mysql_error()) ;
while ( $line = mysql_fetch_assoc($query) )
{
echo "<p><b>PCNE Abstract</b>".$line['abstract_id']."</p>";
echo "<h1>".$line['title']."</h1>";
$authors = Array() ;
for ($i = 1 ; $i <= 6 ; $i++ )
if ( isset($line['author'.$i]) && $line['author'.$i] != '' ) $authors[] = $line['author'.$i].' <sup>'.$i.'</sup>' ;
echo '<b>'.implode(', ',$authors).'</b>' ;
$organizations = Array() ;
for ($i = 1; $i<= 6; $i++)
{
if ( ! isset($line['author'.$i]) || $line['author'.$i] == '' ) continue ; // Check if there is an author, if no go to next loop
if ( isset($line['organization'.$i]) && $line['organization'.$i] != '' ) $organizations[] = ' <sup>'.$i.'</sup> '.$line['organization'.$i] ;
}
echo '<b>'.implode(', ',$organizations).'</b>' ;
echo "<b>Background</b> ";
echo $line['background']."<br>";
echo "<b>Purpose</b> ";
echo $line['purpose']."<br>";
// ...
}
echo "</body>";
echo "</html>";

php report is very slow and crashes in firefox

I have a report that runs and returns 366 records, each containing a thumbnail that is 104 x 80 px. The issue is that the report runs very slowley even though I increased the memory size.
ini_set('memory_limit', '128M');
ini_set('max_execution_time','600');
After writing the SQL query I generate the table items here
generate_table_items($query_all_items);
This then runs through and checks for the image in the columns
function generate_table_items($query){
$columns = array();
$resultset = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$columncount = 0;
$rowcost = 0;
$rowsale = 0;
while ($row = mssql_fetch_assoc($query)) {
if (empty($columns)) {
$columns = array_keys($row);
echo '<tr><th scope="col" >'.implode('</th><th scope="col" >',get_column_name($columns)).'</th></tr>';
$columncount = sizeof(array_keys($row));
}
$resultset[] = $row;
echo '<tr><td>'.implode('</td><td>',report_image_check($row)).'</td></tr>';
if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$colspan = (count($columns)-2);
echo "<tr><th scope='row'>Documents</th><td colspan='$colspan' >";
$PKID = $row['ID'];
if($row['SumOfTotalCost'] || $row['SumOfSalePrice']){
$rowcost += $row['SumOfTotalCost'];
$rowsale += $row['SumOfSalePrice'];
$get_total = true;
}
$query_docs = mssql_query("select documents.* from dbo.documents where documents.Antiquities_id = $PKID") or die ('get docs query failed ' . mssql_get_last_message());
while($row_docs = mssql_fetch_assoc($query_docs)){
$document = "../documents/" . $row_docs['document'];
echo "<a href='$document' title='opens in a new window' target='_blank' >" . $row_docs['document'] . "</a> | ";
} // End while (list docs)
mssql_free_result($query_docs);
echo "</td></tr>";
myflush();
} // End if all items and all items by value report
} // End While
echo '<tr>';
for($i=0;$i < $columncount-4;$i++){
echo '<td> </td>';
}
echo '<td>Total Cost '. $rowcost.'</td>';
echo '<td>Total Sale '. $rowsale.'</td>';
echo '<td>Total Calculated Difference '. ($rowsale-$rowcost).'</td></tr>';
} // End function
function get_column_name($columns){
$newcol = array();
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$thecount = 0;
foreach($columns as $col) {
if($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
// Don't list the PK
} else {
$newcol[] = '<img id="'.$col.'" src="../images/icons/arrow_down.png" alt="click to sort by" onclick="sortby(\''.$col.'\');" />' . $col;
}
$thecount++;
}
/*if(in_array($_SERVER['SCRIPT_NAME'],$scriptname)){
$newcol[] = "documents";
}*/
return $newcol;
}
function report_image_check($row){
global $base_url, $uploaded_images_folder;
$newrow = array();
$imageext = array();
$imageext[0] = ".jpg";
$imageext[1] = ".png";
$imageext[2] = ".gif";
$imageext[3] = ".tiff";
$scriptname = array();
$scriptname[0] = "/reports/all_items.php";
$scriptname[1] = "/reports/all_items_by_value.php";
$PKID = 0;
$thecount = 0;
foreach($row as $rn) {
if(in_array(strtolower(substr($rn,-4)),$imageext)){
$small_img_ext = substr($rn,-4);
$small_img = substr($rn,0,strripos($rn,"."));
$small_img = $small_img . '_140_105' . $small_img_ext;
$newrow[] = '<a href="' . $base_url . $uploaded_images_folder . '/' . $small_img . '" title="click to zoom on image" target="_blank" ><img src="' . $base_url . $uploaded_images_folder . '/' . $rn . '" alt="" width="50px" height="50px" /></a>';
} elseif($thecount == 1 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$PKID = $rn;
} elseif($thecount == 2 && in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='../index.php?template=10&PKID=$PKID' target='_blank' >$PKID (click to view)</a>";
} else {
$newrow[] = $rn;
}
$thecount++;
myflush();
}
/*if (in_array($_SERVER['SCRIPT_NAME'],$scriptname)) {
$newrow[] = "<a href='#&PKID=$PKID' target='_blank' >Documents (click to view)</a>";
}*/
return $newrow;
} // End function
//// Flushing function
function myflush(){
ob_implicit_flush();
ignore_user_abort();
}
Can anyone see an issue with this code or see why it would take so long or why it crashes firefox? Would printing to pdf function work better?
It'll take a long time because you're nesting SQL queries... executing a second SQL query for every result that has been returned by the first query.... Doing a single query with a JOIN should help performance significantly.
Printing to PDF would almost certainly be slower: you'd eithe rneed a lot of code to position everything correctly in the report yourself, or to use one of the libraries that can take HTML and render it to a PDF (as you're already generating HTML anyway at the moment, this would be additional processing)

Categories