0

I'm hitting my server really hard because of a bug somewhere in the following code:

    $qqq = mysql_query("SELECT * FROM coupons WHERE dateExp > CURDATE()");
$isExpired = array();
while($row = mysql_fetch_array($qqq))
{
    $isExpired[] = $row;
}
foreach($isExpired as $exp)
{
    if($exp['id'] == $coupID)
    {
        $expiredConf = 1;
    }
}
if($expiredConf == 1)
{
    echo "<link rel='stylesheet' href='grey.css' type='text/css' />";
}
else
{
    echo "<link rel='stylesheet' href='coupStyle.css' type='text/css' />";
}

I've written code like this a hundred times, and I've compared it to my old examples, but I can't figure out what caused such a major problem.

3
  • How do you know that this code is causing performance issues? Commented Feb 22, 2011 at 7:20
  • Turn on error_reporting, use a profiler, try and run your sql query through a query editor and see how long that takes by itself. Commented Feb 22, 2011 at 7:20
  • Btw, is it supposed to retrieve non expired coupons? You are selecting coupons with an expiry date in the future and putting them in an array named "isExpired", seems a bit strange :) Commented Feb 22, 2011 at 7:31

3 Answers 3

1

I'm not sure how this will work with the surrounding code, but if this part doesn't influence any other areas, you can really condense it down a lot:

$result = mysql_result(sprintf("SELECT id FROM coupons WHERE id = %d AND dateExp > CURDATE()",
                               mysql_real_escape_string($coupID)));

if(!$result){
    $url = 'coupStyle';
} else {
    // Found result
    $url = 'grey';
}

echo '<link rel="stylesheet" href="'.$url.'" type="text/css" />';

If you don't need to select every column from the table, try to only put down one column, and if possible, the table's ID. Also, it is generally advised to avoid using * in select's, and to instead specify which columns you need.

Sign up to request clarification or add additional context in comments.

Comments

0

perhaps you should change your code a bit, cause working with big arrays is always quite slow:

while($row = mysql_fetch_array($qqq))
{
    $isExpired[] = $row;
    if($row['id'] == $coupID)
    {
        $expiredConf = 1;
    }
}

apart from that, your code looks fine. how many records do you have in this recordset?

Comments

0

You can reduce above code lines, No need one extra foreach loop

while($row = mysql_fetch_array($qqq))
{
   $isExpired[] = $row;
   if (in_array($coupID,$row))
   {
     $expiredConf = 1;         
   }

}

1 Comment

with a code like this, isn't it reaally easier to change sql query to "SELECT count(*) FROM coupons WHERE dateExp > CURDATE() and id = $coupId" and check for just 1 record in the recordset? :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.