PHP script appears to be causing high CPU usage on hosting account

Hi, I’m trying to figure out what is causing a high cpu usage on my hosting account. So much that they have shut my site down 3 times. They pointed to several scripts. The main culprates being two randomizer scripts. I’m hoping someone can help me identify what is causing the problem and how to eliminate it with more efficient php :slight_smile:

Here is the first script.

[php]<?php

$host = “";
$user = "
”;
$pass = “";
$dbname = "
**”;
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": “.mysql_error().”
");
mysql_select_db($dbname);

$query = mysql_query(“SELECT * FROM guides”);
$sql = “SELECT id, name, linkraw, thumb, mfg, series, year FROM guides WHERE thumb IS NOT NULL ORDER BY RAND() limit 1”;
$result = mysql_query($sql);
list($id, $name, $linkraw, $thumb, $mfg, $series, $year) = mysql_fetch_array($result);

echo “<a href=”$linkraw"><img src="$thumb" alt="$name - $mfg - $series ($year)" title="$name - $mfg - $series ($year)" width=“110” height=“70” border=“0” />";

mysql_close($connection);

?>[/php]

In this script I am searching a database. In that database I have around 1400 rows to search from in the table. Some of those entries don’t have a thumbnail to show for the random image, so I exluded them in the WHERE thumb IS NOT NULL statement.

Let me know if you need any additional info. One of the problem my hosting account said is that this script is causing too long of a query.

What is $query supposed to be doing? i see it selecting records but the results aren’t being used.

You problem is going to be the ORDER BY RAND()

Here is a potential solution:

According to that solution you shouldn’t use ORDER BY RAND(). Are there any better ways to randomly select something from the database?

how many rows do you have in the database

I have around 1400 rows

mysql_query(‘SELECT @count := COUNT(*) FROM guides’);
mysql_query(‘SET @offset = CONVERT(FLOOR(RAND() * @count), SIGNED)’);
mysql_query(‘PREPARE mystatement FROM “SELECT * FROM guides LIMIT ?, 1”’);
$res = mysql_query(‘EXECUTE mystatement USING @offset’);
$row = mysql_fetch_assoc($res);
print_r($row);

try this see if your cpu goes up

got it from here http://www.electrictoolbox.com/msyql-alternative-order-by-rand/

Sponsor our Newsletter | Privacy Policy | Terms of Service