简体   繁体   中英

SQL requests optimization using OO PHP

I'd like to know if there's a way to fully optimize my SQL requests using OO PHP. Let's take an example, we have 3 object classes named like 3 tables :

  • Product : id, name, price, color...
  • Customer : id, name, surname, email...
  • Cart : id, id_product, id_customer...

All getters and setters are made classically. Now, I only want to display Product[name] and Customer[surname] on my payment page. The corresponding fully optimized request is

SELECT product.name, customer.surname FROM cart INNER JOIN product ON product.id = cart.id_product INNER JOIN customer ON customer.id = cart.id_customer

Where or how can I generate this fully optimized request using OOP ? And not having to retrieve entire objects and treat them later ? Do I have to create a method for each sql request I need to be optimized ? Maybe a request generator ?

Not sure I quite understand, but maybe something like this will jump start you:

function findIt($table,$field,$value)
{
    $table=$mysqli->real_escape_string($table);
    $field=$mysqli->real_escape_string($field);
    $value=$mysqli->real_escape_string($value);
    if ($result = $mysqli->query
        ("SELECT * FROM $table WHERE $field like '$value' LIMIT 0,1;")) 
    {
        return $result->fetch_object();
    }
}    

To call it:

$oCart=findIt('cart','id','SomeID');
echo $oCart->name;

What I was looking for is an ORM because it can manage requests optimization automatically. But ORMs are very constraining. So I have to create a function that generates my requests in a way that's optimized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM