Othman Abahossain
Othman Abahossain

Reputation: 81

PHP multiple queries performance and speed ?

I have this class in PHP, and I have been trying to get all the variables using a function, but the problem is in my database there are more than 1000 rows, so I will use the SELECT statement each time the class called. For instance

        class person
        {
            var $id; // this id will be passed to function get_all()

            var $name;
            var $age;
            var $salary;

            function get_all($id)
            {
                $Query = 'SELECT FROM `person` WHERE `id` = '.$id.'';
                /*
                code to excute the query
                */

                $this->name = somthing;
                $this->age = somthing;
                $this->salary = somthing;
            }
        }

So now I don't know if this method it's the same when I use this method in my PHP code ?

    $Query = 'SELECT * FROM `person`';

    /* excute the Query .. */

    foreach($person_array as $person)
    {
        // I don't know how to make it especially beacause it's dynamic
    }

Is there any possible way to use the same class with use 1 Query ? or if the first method will not make any problem please tell me.

Upvotes: 0

Views: 397

Answers (2)

Brad
Brad

Reputation: 163270

Just modify your first function:

function get_all($id) {
    $Query = 'SELECT * FROM `person`;';
    /*
    code to excute the query
    */
    foreach (/*your foreach statements here*/) {
        $person = new Person; // Create a new person object for each record
        $person->name = somthing;
        $person->age = somthing;
        $person->salary = somthing;
        $persons[] = $person; // Add this person to an array
    }
    return $persons; // Return an array of person objects, containing everyone
}

Using this method is efficient, and will return an array of all the persons you want.

Upvotes: 1

WordsWorth
WordsWorth

Reputation: 872

These two methods are not same.If that id is your indexed/primary key,first one is better only id you have to fire one query.In case you need all rows,second one is better.

Upvotes: 0

Related Questions