php and mysql not showing data, not entering foreach loop - php

I am having trouble with modifying a php application to have pagination. My error seems to be with my logic, and I am not clear exactly what I am doing incorrectly. I have had before, but am not currently getting errors that mysql_num_rows() not valid result resource
and that invalid arguments were supplied to foreach. I think there is a problem in my logic which is stopping the results from mysql from being returned.
All my "test" echos are output except testing while loop. A page is generated with the name of the query and the word auctions, and first and previous links, but not the next and last links. I would be grateful if a more efficient way of generating links for the rows in my table could be pointed out, instead of making a link per cell. Is it possible to have a continuous link for several items?
<?php
if (isset($_GET["cmd"]))
$cmd = $_GET["cmd"]; else
die("You should have a 'cmd' parameter in your URL");
$query ='';
if (isset($_GET["query"])) {
$query = $_GET["query"];
}
if (isset($_GET["pg"]))
{
$pg = $_GET["pg"];
}
else $pg = 1;
$con = mysql_connect("localhost","user","password");
echo "test connection<p>";
if(!$con) {
die('Connection failed because of' .mysql_error());
}
mysql_query('SET NAMES utf8');
mysql_select_db("database",$con);
if($cmd=="GetRecordSet"){
echo "test in loop<p>";
$table = 'SaleS';
$page_rows = 10;
$max = 'limit ' .($pg - 1) * $page_rows .',' .$page_rows;
$rows = getRowsByProductSearch($query, $table, $max);
echo "test after query<p>";
$numRows = mysql_num_rows($rows);
$last = ceil($rows/$page_rows);
if ($pg < 1) {
$pg = 1;
} elseif ($pg > $last) {
$pg = $last;
}
echo 'html stuff <p>';
foreach ($rows as $row) {
echo "test foreach <p>";
$pk = $row['Product_NO'];
echo '<tr>' . "\n";
echo '<td>'.$row['USERNAME'].'</td>' . "\n";
echo '<td>'.$row['shortDate'].'</td>' . "\n";
echo '<td>'.$row['Product_NAME'].'</td>' . "\n";
echo '</tr>' . "\n";
}
if ($pg == 1) {
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?pg=1'> <<-First</a> ";
echo " ";
$previous = $pg-1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$previous'> <-Previous</a> ";
}
echo "---------------------------";
if ($pg == $last) {
} else {
$next = $pg+1;
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a> ";
echo " ";
echo " <a href='{$_SERVER['PHP_SELF']}?pg=$last'>Last ->></a> ";
}
echo "</table>\n";
}
echo "</div>";
function getRowsByProductSearch($searchString, $table, $max) {
$searchString = mysql_real_escape_string($searchString);
$result = mysql_query("SELECT Product_NO, USERNAME, ACCESSSTARTS, Product_NAME, date_format(mycolumn, '%d %m %Y') as shortDate FROM {$table} WHERE upper(Product_NAME) LIKE '%" . $searchString . "%'" . $max);
if($result === false) {
echo mysql_error();
}
$rows = array();
while($row = mysql_fetch_assoc($result)) {
echo "test while <p>";
$rows[] = $row;
}
return $rows;
mysql_free_result($result);
}
edit: I have printed out the mysql error of which there was none. However 8 "test whiles" are printed out, from a database with over 100 records. The foreach loop is never entereded, and I am unsure why.

The problem (or at least one of them) is in the code that reads:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = mysql_num_rows($rows);
The $numRows variable is not a MySQL resultset, it is just a normal array returned by getRowsByProductSearch.
Change the code to read:
$rows = getRowsByProductSearch($query, $table, $max);
$numRows = count($rows);
Then it should at least find some results for you.
Good luck, James
Hi there,
The next problem is with the line that reads:
$last = ceil($rows/$page_rows);
It should be changed to read:
$last = ceil($numRows / $page_rows);
Would recommend adding the following lines to the start of you script at least while debugging:
ini_set('error_reporting', E_ALL | E_STRICT);
ini_set('display_errors', 'On');
As that would have thrown up a fatal error and saved you a whole lot of time.

if (!(isset($pg))) {
$pg = 1;
}
How is $pg going to get set? You don't appear to be reading it from $_GET. If you're relying on register_globals: don't do that! Try to read it from $_GET and parse it to a positive integer, falling back to '1' if that fails.
<a href='{$_SERVER['PHP_SELF']}?pg=$next'>Next -></a>
You appear to be losing the other parameters your page needs, 'query' and 'cmd'.
In general I'm finding it very difficult to read your code, especially the indentation-free use of echo(). Also you have untold HTML/script-injection vulnerabilities every time you "...$template..." or .concatenate a string into HTML without htmlspecialchars()ing it.
PHP is a templating language: use it, don't fight it! For example:
<?php
// Define this to allow us to output HTML-escaped strings painlessly
//
function h($s) {
echo(htmlspecialchars($s), ENT_QUOTES);
}
// Get path to self with parameters other than page number
//
$myurl= $_SERVER['PHP_SELF'].'?cmd='.urlencode($cmd).'&query='.urlencode($query);
?>
<div id="tableheader" class="tableheader">
<h1><?php h($query) ?> Sales</h1>
</div>
<div id="tablecontent" class="tablecontent">
<table border="0" width="100%"> <!-- width, border, cell width maybe better done in CSS -->
<tr>
<td width="15%">Seller ID</td>
<td width="10%">Start Date</td>
<td width="75%">Description</td>
</tr>
<?php foreach ($rows as $row) { ?>
<tr id="row-<?php h($row['Product_NO']) ?>" onclick="updateByPk('Layer2', this.id.split('-')[1]);">
<td><?php h($row['USERNAME']); ?></td>
<td><?php h($row['shortDate']); ?></td>
<td><?php h($row['Product_NAME']); ?></td>
</tr>
<?php } ?>
</table>
</div>
<div class="pagercontrols">
<?php if ($pg>1) ?>
<<- First
<?php } ?>
<?php if ($pg>2) ?>
<-- Previous
<?php } ?>
<?php if ($pg<$last-1) ?>
Next -->
<?php } ?>
<?php if ($pg<$last) ?>
Last ->>
<?php } ?>
</div>
Is it possible to have a continuous link for several items?
Across cells, no. But you're not really using a link anyway - those '#' anchors don't go anywhere. The example above puts the onclick on the table row instead. What exactly is more appropriate for accessibility depends on what exactly your application is trying to do.
(Above also assumes that the PK is actually numeric, as other characters may not be valid to put in an 'id'. You might also want to consider remove the inline "onclick" and moving the code to a script below - see "unobtrusive scripting".)

This is wrong:
if($cmd=="GetRecordSet")
echo "test in loop\n"; {
It should be:
if($cmd=="GetRecordSet") {
echo "test in loop\n";

In your getRowsByProductSearch function, you return the result of mysql_error if it occurs. In order to debug the code, maybe you can print it instead, so you can easily see what the problem is.

Related

Separate MySQL results into Divs using while loop

Just beginning PHP to bear with me.
Results I'm trying to achiever:
I have a table of YouTube URL's and MetaData.
Trying to build this:
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
<div class="slide">
<iframe></iframe>
<iframe></iframe>
</div>
Two videos per slide, then I'm going to paginate through results using Deck.js.
I suspect I'm going about this completely the wrong way, not that experienced at programmin g logic;
while($data = mysql_fetch_array($result)) {
for ($counter = 1; $counter<=2; $counter++) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
/* If Video 1, increment counter for 2nd video */
if ($counter == 1) {
$counter++;
}
/* If Video 2, close div and reset counter */
else if ($counter == 2) {
echo "</div>";
$counter = 1;
}
/* If error break out */
else {
echo "</div>";
break;
}
}
}
Basically trying to nest loops to keep track of how many videos per div and start a new one when a div has two.
I've tried a few different ways, this being the latest. Results in:
<div class="slide">
<iframe></iframe>
<div class="slide>
<iframe></iframe>
Hit the blank wall now, not sure what to try next. Willing to use/learn any method to accomplish the results, just not sure where to go at this point.
Cheers.
You could remove the second loop all together using the % operator (modulus). The idea is that a % b === 0 then the number a was evenly divisible by b. Using this, you can easily check for even or odd or every Nth row.
$k = 1;
echo "<div class=\"slide\">";
while($data = mysql_fetch_array($result)) { // you should really change to mysqli or PDO
if($k % 3 === 0){
echo "</div>";
echo "<div class=\"slide\">";
}
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
$k++;
}
echo "</div>";
Put the echo <div> before the for loop (still inside the while loop) and the </div> after the for loop
In your while loop you're retrieving just one row, but then you're iterating over it twice with a nested loop. Do away with the inner loop and just use a flip-flop variable to track left and right. I think this will do what you want:
$left=true; // track whether we're emitting HTML for left or right video
while($data = mysql_fetch_array($result)) {
if ($left) {
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
}
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
if (!$left) {
echo "</div>";
}
$left = !$left; // invert $left to indicate we're emitting the right iFrame
}
// end of loop. If we had an odd number of
// videos, tidy up the HTML
if (!$left) {
echo "</div>";
}
PHPFiddle
<?php
$x = 10;
$counter = 0;
while($x > 0)
{
if($counter != 0 && $counter % 2 == 0)
{
echo "ENDOFSLIDE</br>";
}
if($counter == 0 || $counter % 2 == 0)
{
echo "SLIDE</br>";
}
echo "iframe => $x </br>";
$x--;
$counter++;
}
echo "ENDOFSLIDE";
?>
It won't work because the for loop is inside the fetch loop for the SQL data. The second iteration of the for loop does not have a new SQL row. A better solution would be to capture the common column that identifies the two videos (the title) and generate a new div whenever that value changes. Try something like this, which will work for any number of SQL rows with the same title. This will also give proper results if the SQL query returns no rows and will handle the potential of a title with only one URL - which could get ugly if you merely flip-flop and end up with URLs on the wrong title. Of course, as in your current solution, your SQL query must ORDER BY VIDEO_TITLE so the rows are adjacent. I didn't run it, but should be close.
$lastTitle = "";
$n = 0; //count SQL rows processed
while($data = mysql_fetch_array($result)) {
// See if the title changed from last
if( $data['VIDEO_TITLE'] != $lastTitle ) {
// if we processed any rows, must end the current div before starting a new one
if( $n > 0 )
echo "</div>";
echo "<div class=\"slide\">";
echo "<h3>" . $data['VIDEO_TITLE'] . "</h3>";
//save the title as last title
$lastTitle = $data['VIDEO_TITLE'];
}
$n++; //count the SQL row
echo "<iframe width=\"560\" height=\"315\" src=\"" . $data['VIDEO_URL'] . "\" frameborder=\"0\" allowfullscreen></iframe>";
}
if( $n > 0 )
echo "</div>";

How to speedup by code?

is there a way to speed up my code? It takes about 15 seconds to load ... I don't really see a way to reduce my code... I just thought about inserting the values into database, so the user does not have to load new info every time.. but the thing is that my cron only allows 1 load per hour ... by loading new info on every load it gives me fresh information..
$q1=mysql_query("SELECT * FROM isara");
while($r1=mysql_fetch_array($q1)){
$named=$r1['name'];
$idd=$r1['id'];
$descd=$r1['desc'];
$online=check_online($named);
$char = new Character($r1['name'],$r1['id'],$r1['desc']);
if($online == "online"){
$char->rank = $i++;
}
else{
$char->rank = 0;
}
$arr[] = $char;
}
?>
<br />
<h2 style="color:green">Online enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank>=1){
echo "<a style=\"color:green\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
<br />
<h2 style="color:red">Offline enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank==0){
echo "<a style=\"color:red\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
As I wrote in the comment, fetch the page once instead of once for every name in the database.
Pseudo code for my comment:
users = <get users from database>
webpage = <get webpage contents>
for (user in users)
<check if user exists in webpage>
As mentioned in the comments you're calling a webpage for each entry in your database, assuming that's about 2 seconds per call it's going to slow you down a lot.
Why don't you call the page once and pass the contents of it into the check_online() function as a parameter so your code would look something like this which will speed it up by quite a few magnitudes:
$content=file_get_contents("http://www.tibia.com/community/?subtopic=worlds&worl‌​d=Isara",0);
$q1=mysql_query("SELECT * FROM isara");
while($r1=mysql_fetch_array($q1)){
$named=$r1['name'];
$idd=$r1['id'];
$descd=$r1['desc'];
$online=check_online($named,$content);
$char = new Character($r1['name'],$r1['id'],$r1['desc']);
if($online == "online"){
$char->rank = $i++;
}
else{
$char->rank = 0;
}
$arr[] = $char;
}
?>
<br />
<h2 style="color:green">Online enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank>=1){
echo "<a style=\"color:green\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
<br />
<h2 style="color:red">Offline enemies</h2>
<?php
foreach ($arr as $char) {
if($char->rank==0){
echo "<a style=\"color:red\" href=\"http://www.tibia.com/community/?subtopic=characters&name=$char->name\">";
echo $char->name." ";
echo "</a>";
echo level($char->name)."<b> ";
echo vocation($char->name)."</b> (<i>";
echo $char->desc." </i>)<br />";
}
}
?>
and your check_online() function would look something like this:
function check_online($name,$content){
$count=substr_count($name, " ");
if($count > 0){ $ex=explode(" ",$name); $namez=$ex[1]; $nameused=$namez; }
else{ $nameused=$name; }
if(preg_match("/$nameused/",$content)){ $status="online"; }
else{ $status="offline"; }
return $status;
}
You can also do the following to make it faster
Stop using select * which is very bad on innodb
Put better indexes on your database to make the recordset return faster
Install PHP 5.4 as it's faster especially as you're creating a new object in each iteration
Use a byte code accelerator/cache such as xdebug
you should avoid using distinct (*) keyword in your SQL Query
for more information read this http://blog.sqlauthority.com/category/sql-coding-standards/page/2/

Using php's count () command to count the result of an if statement

I am trying to work my head round this, I am using the following code to check the answers to a quiz and output either CORRECT or INCORRECT depending on the result of the comparison, and if the answer field is black (which only comes from the feedback form) a different message is displayed.
I cant quite work out how to apply the php count function in this situation though, what im trying to get it to do it count the amount of CORRECT and INCORRECT answers and add the two together, and then I can work out a % score from that.
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT * FROM itsnb_chronoforms_data_answerquiz a, itsnb_chronoforms_data_createquestions
q WHERE a.quizID='$quizID' AND a.userID='$userID' and q.quizID=a.quizID and
a.questionID = q.questionID ORDER BY a.cf_id ASC" or die("MySQL ERROR: ".mysql_error());
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}}
?>
Iv found this example and have been trying to work out how to work it in, but cant think how to count the results of an if statement with it ?.
<?php
$people = array("Peter", "Joe", "Glenn", "Cleveland");
$result = count($people);
echo $result;
?>
Just increment two counters
$correct_answers = 0;
$incorrect_answers = 0;
while ($row = mysql_fetch_array($result)) {
if ($row['correctanswer'] == '') {...
} elseif ($row['correctanswer'] == $row['quizselectanswer']) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$correct_answers++;
} else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$incorrect_answers++;
}
}
Simply increase some counter in each branch of your if/elseif/else construct...
$counters = array( 'blank'=>0, 'correct'=>0, 'incorrect'=>0 );
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ( ''==$row['correctanswer'] ) {
echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';
$counters['blank'] += 1;
}
elseif ( $row['correctanswer']==$row['quizselectanswer'] ) {
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';
$counters['correct'] += 1;
}
else {
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
$counters['incorrect'] += 1;
}
}
echo '#correct answers: ', $counters['correct'];
How about creating a variable with a count of correct answers? For each question you loop through, increment the value by one.
<?php
$correct_answers = 0;
while($questions) {
if($answer_is_correct) {
// Increment the number of correct answers.
$correct_answers++;
// Display the message you need to and continue to next question.
}
else {
// Don't increment the number of correct answers, display the message
// you need to and continue to the next question.
}
}
echo 'You got ' . $correct_answers . ' question(s) right!';
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT ... ";
$result = mysql_query($query) or die(mysql_error());
$countCorrect = 0;
$countIncorrect = 0;
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
if ($row['correctanswer'] == ''){echo '<tr><td style="color:blue;">Thankyou for your feedback</td></tr>';}
elseif ($row['correctanswer'] == $row['quizselectanswer']){
$countCorrect++;
echo '<tr><td style="font-weight:bold; color:green;">CORRECT</td></tr>';}
else {
$countIncorrect++;
echo '<tr><td style="font-weight:bold; color:red;">INCORRECT</td></tr>';
}
}
echo ((int)($countCorrect/($countIncorrect + $countCorrect) * 100)) . "% answers were correct!" ;
?>

php working locally and remotely on own hosting, but not remotely on client's hosting

I'm not good with PHP, so please bear with me. I have the following code:
<?php $thisPage="designers";
include("phpincludes/header.php") ?>
<div id="contentLeft">
<?echo "<h2><a href='designer_display.php?d_name=".$_GET['d_name']."'>" . $_GET['d_name']. "</a></h2>";?>
<?
error_reporting(0);
require_once "phpincludes/connection.php";
$designer = $_GET['d_name'];
// Category Selection Start.
$cat_qry = "SELECT DISTINCT (
`own_category`
)
FROM `products`
WHERE `designer` ='".$designer."' && own_category != ''";
$rs_qry = mysql_query($cat_qry);
$i = 0;
while($rec_qry = mysql_fetch_array($rs_qry))
{
if($i==0)
$first_cat = $rec_qry['cat_name'];
$cat_name[$i]=$rec_qry['cat_name'];
$i++;
}
// Category Selection Start.
$cat_name = $_GET['catName1'];
$cat_qry = "SELECT DISTINCT (
`own_category`
)
FROM `products`
WHERE `designer` ='".$designer."' && own_category != ''";
//"select * from categories";
$rs_qry = mysql_query($cat_qry);
$rec_no = mysql_affected_rows();
/*if($_GET["catName1"]=="")
$catName = $first_cat;
else
$catName = $cat_name;*/
$n1 = 1;
echo "<ul id=\"designers\">";
while($rec_qry = mysql_fetch_array($rs_qry))
{
$cate_name = str_replace('_',' ',$rec_qry['own_category']);
//print_r($cate_name[1]);
if($rec_qry["own_category"]!= $_GET['catName'])
echo "<li><A HREF='d_items.php?no=".$n1."&d_name=".$designer."&catName=".$rec_qry["own_category"]."'>".strtoupper($cate_name)."</A></li>";
else
echo "<li><A HREF='d_items.php?no=".$n1."&d_name=".$designer."&catName=".$rec_qry["own_category"]."'><font color='#8d9354'>".strtoupper($cate_name)."</font></a></li>";
if($rec_qry["own_category"]== $_GET['catName'])
{
$query="SELECT A.photo_filename, A.photo_title, B.dc_cat_name FROM displays A
LEFT JOIN displays_categories B ON B.dc_display_photos = A.photo_filename
WHERE dc_cat_name ='".$rec_qry["cat_name"]."'";
$query="SELECT B.pro_name, B.own_category, B.own_photo_filename from categories as A LEFT JOIN
products as B ON A.cat_name = B.own_category
where cat_name ='".$_GET["catName"]."' and designer ='".$designer."' order by B.pro_name";
$rs1_qry = mysql_query($query);
echo "<ul class=\"items\">";
while($row = mysql_fetch_array($rs1_qry))
{
if ($designer == "Jardan") {
$p1name = str_ireplace($designer,'',$row["pro_name"]);
$pname = substr($p1name, 0, -3);
} else {
$pname = str_ireplace($designer,'',$row["pro_name"]);
}
if($_GET['ProName'] != $row["pro_name"])
echo "<li><A HREF='d_item_details.php?d_name=".$designer."&ProName=".$row['pro_name']."&catName1=".$rec_qry['own_category']."&catName=".$rec_qry['own_category']."'>".$pname."</A></li>";
else
echo "<li><A HREF='d_item_details.php?d_name=".$designer."&ProName=".$row['pro_name']."&catName1=".$rec_qry['own_category']."&catName=".$rec_qry['own_category']."'><font color='#fff'>".$pname."</font></A></li>";
}
echo "</ul>";
}
}
echo "</ul>";
$f=1;
$recnm = $_GET['ProName'];
$owncat = $_GET['catName1'];
$photo_title = $_GET['ptitle'];
$query2="SELECT pro_code, pro_dimensions, own_photo_filename, designer_pdf, palette FROM products
WHERE pro_name ='".$recnm."' and own_category ='".$owncat."'";
$rt2=mysql_query($query2);
echo mysql_error();
?>
</div>
<div id="contentRight">
<?
while($row2 = mysql_fetch_array($rt2))
{
?>
<?$d = explode(' ',$designer);
for($p=0;$p<count($d);$p++)
{
$des.=$d[$p];
}
if ($designer == "Playstar") {
$p2name = str_ireplace($designer,'',$recnm);
$poname = substr($p2name, 0, -3);
} else {
$poname = str_ireplace($designer,'',$recnm);
}
?>
<img class="lighting" src="img/designers/<?echo $des."/".$row2['own_photo_filename'];?>.jpg" />
<div class="mailerBtn"><h4>ENQUIRE</h4>
<h4>Download Product PDF</h4></div>
<h3><?echo $poname;?></h3>
<p>
<?
echo "<b>Product code:</b> ". $row2['pro_code']."<BR>";
if ($designer == "Playstar") {
echo $row2['pro_dimensions'];
} else {
echo "<b>Dimensions:</b> ". $row2['pro_dimensions'];
} ?>
</p>
<? if($row2[4]=='yes') {
?>
<img class="palette" src="img/designers/<?echo $des."/".$row2['own_photo_filename'];?>-palette.jpg" />
<? } ?>
<?}?>
<?php include("phpincludes/base.php") ?>
Much of the code was written by someone else, but I've been modifying it in a couple of ways. It works locally (on XAMP) and on my personal site where I've been hosting it as a test site.
But when i uploaded it to the client's host, this page stops abruptly at echo "<ul class=\"items\">"; - roughly line 73. I can't see what's stopping it from running properly.
Some assistance would be gratefully received!
MTIA.
That's hard to tell. It's very obviously something with the clients setup.
Taking a wild guess, that client is still running PHP4. Because after line 73 you have a call to str_ireplace which wasn't available for that.
You would likely get a fatal error for this one. And this is the right avenue for investigation here. Add this on top for debugging (instead of error_reporting(0) which is not so helpful):
error_reporting(E_ALL|E_WARNING);
And ask for errors. Better yet, provide a custom error handler which prints out something shiny for end user-type clients. Otherwise ask for the error.log which should contain the exact error likewise.
You should avoid using the "short tags" <? and replace with the regular <?php tags. At a minimum, on that line not having a space after the "?" is asking for trouble, but overall you should just replace the short tags as they can cause trouble for various reasons and many installations do not have them enabled by default.
FYI, one specific case where they often cause trouble is for XHTML documents, if the xml declaration isn't printed with PHP, it will throw an error. Now with HTML5 I guess this will be less of an issue, but IMHO, best practice would be to avoid them.
Glad you got it working, but I wouldn't be using this code in production on your clients web host.
$f=1;
$recnm = $_GET['ProName'];
$owncat = $_GET['catName1'];
$photo_title = $_GET['ptitle'];
$query2="SELECT pro_code, pro_dimensions, own_photo_filename, designer_pdf, palette FROM products WHERE pro_name ='".$recnm."' and own_category ='".$owncat."'";
This and all the other queries here are vulnerably to sql injection. (if I passed in catName1='; DELETE * FROM products where 1=1 or '2'='2)
You need to either convert the queries to paramaterised queries, or use mysql_real_escape_string.
ie
$owncat = mysql_real_escape_string($_GET['ProName']);

PHP Function givine IE problems

I have a small PHP function that is called from one of my pages.
function ratingDetails($uid, $align, $width) {
$queryFull = "SELECT * FROM rating WHERE uid = $uid";
$resultFull = mysql_query($queryFull);
//START DISPLAY TABLE IF RESULTS
if(mysql_num_rows($resultFull) > 0) {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"550\">\n";
echo "<tr bgcolor=\"#6699cc\"><th>STARS</th><th>DATE RATED</th><th>COMMENT</th><th>RATED BY</th></tr>\n";
while($rowFull = mysql_fetch_array($resultFull)) {
$rating = $rowFull['rating'];
$comment = $rowFull['comment'];
$datePosted = date("M j, Y", $rowFull['date']);
$rid = $rowFull['raterID'];
$rater = getUsername($rid);
//SHOW STARS
if($rating == 0) { $stars = "notYet.jpg"; }
if($rating == 1) { $stars = "starOne.jpg"; }
if($rating == 1.5) { $stars = "starOneHalf.jpg"; }
if($rating == 2) { $stars = "starTwo.jpg"; }
if($rating == 2.5) { $stars = "starTwoHalf.jpg"; }
if($rating == 3) { $stars = "starThree.jpg"; }
if($rating == 3.5) { $stars = "starThreeHalf.jpg"; }
if($rating == 4) { $stars = "starFour.jpg"; }
if($rating == 4.5) { $stars = "starFourHalf.jpg"; }
if($rating == 5) { $stars = "starFive.jpg"; }
//DISPLAY IT ALL
echo "<tr><td width=\"10\"><img src=\"/images/rating/$stars\" width=\"105\" height=\"20\" /></td>";
echo "<td width=\"75\" align=\"center\">$datePosted</td><td>$comment</td><td width=\"85\">$rater</td></tr>\n";
}//END WHILE
echo "</table>\n";
} //END IF
else {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"8\" width=\"550\">\n";
echo "<tr><td align=\"center\"><span class=\"blue\">NO REVIEWS OR RATINGS FOR THIS DISTRIBUTOR</span></td></tr></table>\n";
} //END IF ELSE
}
But when it runs in IE (7 or 8), it throws this error:
A script on this page is causing Internet Explorer to run slowly. Bla bla bla...
I call this function from two pages and both cause the same error. If I remove the call from the page, the page loads fine.
There is no javascript involved with the pages in question...
Help, help, help... I don't have much hair left...
Rick
What's happening is that it's taking a long time to execute your script. IE is waiting for output from the server but it's taking a long time.
You may want to try either a call to flush() every row (or maybe every 25 rows using the modulus operator) or using ob_implicit_flush() to turn on implicit flushing. That way you have data continually coming back to the browser (I assume you have a huge amount of data). You probably will also need to call set_timeout(0) to disable the 30 second time limit on your script.
The first thing I would do is get rid of all those IF statements for the stars, either using an array for them or a switch statement, either of which would reduce the processing required for your script. An array would be my approach. Your code would look something like the following:
function ratingDetails($uid, $align, $width) {
$queryFull = "SELECT * FROM rating WHERE uid = $uid";
$resultFull = mysql_query($queryFull);
// Declare the array for the stars.
$astars = array(
0=> "notYet.jpg",
1=> "starOne.jpg",
1.5=> "starOneHalf.jpg",
2=> "starTwo.jpg",
2.5=> "starTwoHalf.jpg",
3=> "starThree.jpg",
3.5=> "starThreeHalf.jpg",
4=> "starFour.jpg",
4.5=> "starFourHalf.jpg",
5=> "starFive.jpg"
);
//START DISPLAY TABLE IF RESULTS
if(mysql_num_rows($resultFull) > 0) {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"550\">\n";
echo "<tr bgcolor=\"#6699cc\"><th>STARS</th><th>DATE RATED</th><th>COMMENT</th><th>RATED BY</th></tr>\n";
while($rowFull = mysql_fetch_array($resultFull)) {
$rating = $rowFull['rating'];
$comment = $rowFull['comment'];
$datePosted = date("M j, Y", $rowFull['date']);
$rid = $rowFull['raterID'];
$rater = getUsername($rid);
$stars = $astars[$rating];
//DISPLAY IT ALL
echo "<tr><td width=\"10\"><img src=\"/images/rating/$stars\" width=\"105\" height=\"20\" /></td>";
echo "<td width=\"75\" align=\"center\">$datePosted</td><td>$comment</td><td width=\"85\">$rater</td></tr>\n";
}//END WHILE
echo "</table>\n";
} //END IF
else {
echo "<table class=\"ratingTable\" align=\"center\" border=\"1\" cellspacing=\"0\" cellpadding=\"8\" width=\"550\">\n";
echo "<tr><td align=\"center\"><span class=\"blue\">NO REVIEWS OR RATINGS FOR THIS DISTRIBUTOR</span></td></tr></table>\n";
} //END IF ELSE
The decimals may cause a problem in the array; if so, you can enclose the keys in quotes; e.g., "1.5"=>"starOneHalf.jpg"
The other thing you could do is create a variable for the HTML output instead of echoing the output every line, and then just echo the output at the end.
I found my problem...
The table within my function was assigned a css class. This particular css class contained a behavior, which called PIE.htc. Apparently, this caused some sort of IE melt down whenever it was called. I removed PIE (bummer, no more rounded corners or shadows in IE) and my problem is solved!!!
Thanks to everyone who provided assistance along the way!!!

Categories