Page 1 of 1

How can I reduce lines of code per file?

Posted: Thu Oct 05, 2006 4:20 pm
by waradmin
All over one of my files (profile.php) I have database query's in the form of:

Code: Select all

$result = mysql_query("SELECT * FROM loginphp WHERE Uname='{$_SESSION[Uname]}'") or die(mysql_error());
$row = mysql_fetch_array( $result );
and

Code: Select all

$result = mysql_query("SELECT * FROM friends WHERE global_id='$_GET[id]' AND friend_global_id='$global_id'") or die(mysql_error());
$num_rows = mysql_num_rows($result);
Is there a way to just throw each one of these into a file and call that file each time I need the specific query run?

I mean there are all kinds of querys on tables such as friends, loginphp, profile_photo, wall, education, general and having to constantly add in the query is annoying, I would like to have a master file of my database query's and be able to call the one I want when I want it to reduce lines of code in my files, and eliminate the need for me to type in the query's over and over.

Thanks
-Steve

Posted: Thu Oct 05, 2006 4:29 pm
by danharibo
make a php file containg all you querys, then call like this:

Code: Select all

DoUserQuery("Bob321");
Would return A mysql Resource containg the user Bob321 :)

Posted: Thu Oct 05, 2006 4:32 pm
by waradmin
Im not following, how does it know which one to call when each is in the form of $result?

Posted: Thu Oct 05, 2006 4:36 pm
by danharibo
Put them all in diffrent Functons like
DoUserQuery()
DoNewsQuery()
Etc..

Posted: Thu Oct 05, 2006 4:37 pm
by s.dot
You don't want to actually DO the queries before you need them, but you could make a function like this...

Code: Select all

function do_user_query($what)
{
    switch($what)
    {
        case 'bob321':
        return mysql_query("SELECT * FROM `users` WHERE `username` = 'bob321'");
        break;
    }
}
Although, I don't really see that being practical.

Posted: Thu Oct 05, 2006 4:46 pm
by waradmin
Seems more practical than what I am doing now.

Posted: Thu Oct 05, 2006 7:58 pm
by daedalus__
It's time to read about OOP. :D

Posted: Thu Oct 05, 2006 9:14 pm
by waradmin
Daedalus- wrote:It's time to read about OOP. :D
That is one of the next things I am learning about in my Computer Science: C++ lecture series, so I may wait until I learn about C++ OOP to apply it to PHP, because much of C++ is similar to PHP as far as syntax and concepts go.