homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / Databases
Forum Library, Charter, Moderator: open

Databases Forum

Frequent statements make for bulky and unmanagable code
Cutting the code up to code

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

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)

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)

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)

This is perfect!

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

Thank you.

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / Databases
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved