Welcome to WebmasterWorld Guest from

Forum Moderators: open

Message Too Old, No Replies

Frequent statements make for bulky and unmanagable code

Cutting the code up to code



6:58 pm on May 20, 2007 (gmt 0)

5+ Year Member

Hello, I'm trying to clean up my code to make it easier to manage and read, and I've come across a lot of instances where I need to count how many times something has happened.

I'm using the following structure, but it takes up two lines which basically DOUBLES the size and bulk of my code. I also imagine it might not be the fastest way to do it.

$clicks_in_30_min=mysql_fetch_array(mysql_query("SELECT SUM(clicked) FROM links WHERE ip='$ip'"));

Any suggestions?



3:05 am on May 21, 2007 (gmt 0)

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 5+ Year Member

You're not going to be able to make it too much 'shorter'. I guess you can use mysql_result [php.net] instead of mysql_fetch_array(). The only problem here is that by making it all fit onto one line, you are making it harder to read the code. It would be much better if you split a few things up to make it easier to follow:

#don't forget to escape your query variables!
$query = "SELECT SUM(clicked) FROM links WHERE ip='".[url=http://www.php.net/mysql-real-escape-string]mysql_real_escape_string[/url]($ip)."'";
$result = mysql_query($query) or die('Query Failed');

Obviously this is a personal choice, but even though it is more lines, it is much neater, at least for me :)


3:15 am on May 21, 2007 (gmt 0)

WebmasterWorld Senior Member vincevincevince is a WebmasterWorld Top Contributor of All Time 10+ Year Member

Use a function... and then you get it down to one line each time it happens. If parts of the SQL are always the same, you can always hardcode them into your function and only send what's changed.

$clicks_in_30_min=mysql_get_number("SELECT SUM(clicked) FROM links WHERE ip='$ip'");

function mysql_get_number($sql)
return $r[0];


2:59 pm on May 21, 2007 (gmt 0)

5+ Year Member

This is perfect!

Both steller ideas, this will help me greatly with my code.

Thank you.


Featured Threads

Hot Threads This Week

Hot Threads This Month