2

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 ?

2
  • Perhaps you could look into ORMs, which do this for you, including various optimisations. Propel supports eager relation loading (retrieving all tables in one go rather than each separately) and you can lazy load columns (makes a separate request for certain columns on the basis you don't often use them, handy for BLOBs etc). Have a look at Doctrine, though I don't know that one.
    – halfer
    Sep 26, 2013 at 8:09
  • @halfer I want to know what's in my code, ORMs are taking this from me Sep 26, 2013 at 8:13

2 Answers 2

3

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;
2
  • That's quite what I want, but it doesn't manage joints. I have to make my own request generator, so ? Sep 26, 2013 at 8:19
  • 1
    As I said it was a jump start to get you going in the right direction. You can use my model and expand it to support joins.
    – sskoko
    Sep 26, 2013 at 8:45
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.